/// <summary>
 /// 添加Rye框架对Redis缓存的支持
 /// </summary>
 /// <param name="serviceCollection"></param>
 /// <param name="redisClient">Redis 客户端访问对象</param>
 /// <returns></returns>
 private static IServiceCollection AddRedisCache(IServiceCollection serviceCollection, CSRedisClient redisClient)
 {
     //将Redis分布式缓存服务添加到服务中
     //if(action == null)
     //{
     //    var congiration = serviceCollection.GetSingletonInstance<IConfiguration>();
     //    action = options =>
     //    {
     //        congiration.GetSection("Framework:Redis").Bind(options);
     //    };
     //}
     RedisHelper.Initialization(redisClient);
     serviceCollection.AddSingleton <IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));
     return(serviceCollection);
 }
Exemplo n.º 2
0
 static RedisBase()
 {
     redisClient = RedisProxyAgent.GetClient();
 }
Exemplo n.º 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddSession();
            //代替HttpContext.Current
            services.AddHttpContextAccessor();
            //缓存缓存选择
            if (Configuration.GetSection("SystemConfig:CacheProvider").Value != Define.CACHEPROVIDER_REDIS)
            {
                services.AddMemoryCache();
            }
            else
            {
                //redis 注入服务
                string redisConnectiong = Configuration.GetSection("SystemConfig:RedisConnectionString").Value;
                // 多客户端 1、基础 2、操作日志
                var redisDB1 = new CSRedisClient(redisConnectiong + ",defaultDatabase=" + 0);
                BaseHelper.Initialization(redisDB1);
                var redisDB2 = new CSRedisClient(redisConnectiong + ",defaultDatabase=" + 1);
                HandleLogHelper.Initialization(redisDB2);
                services.AddSingleton(redisDB1);
                services.AddSingleton(redisDB2);
            }
            #region 依赖注入
            //注入数据库连接
            services.AddScoped <Chloe.IDbContext>((serviceProvider) =>
            {
                return(DBContexHelper.Contex());
            });
            #region 注入 Quartz调度类
            services.AddSingleton <JobCenter>();
            services.AddSingleton <JobExecute>();
            //注册ISchedulerFactory的实例。
            services.AddSingleton <ISchedulerFactory, StdSchedulerFactory>();
            services.AddSingleton <IJobFactory, IOCJobFactory>();
            #endregion
            //注入SignalR实时通讯,默认用json传输
            services.AddSignalR(options =>
            {
                //客户端发保持连接请求到服务端最长间隔,默认30秒,改成4分钟,网页需跟着设置connection.keepAliveIntervalInMilliseconds = 12e4;即2分钟
                options.ClientTimeoutInterval = TimeSpan.FromMinutes(4);
                //服务端发保持连接请求到客户端间隔,默认15秒,改成2分钟,网页需跟着设置connection.serverTimeoutInMilliseconds = 24e4;即4分钟
                options.KeepAliveInterval = TimeSpan.FromMinutes(2);
            });
            ////注册html解析
            //services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            ////注册特性
            //services.AddScoped<HandlerLoginAttribute>();
            //services.AddScoped<HandlerAuthorizeAttribute>();
            ////ajax不能使用注入
            ////services.AddScoped<HandlerAjaxOnlyAttribute>();
            //services.AddScoped<HandlerAdminAttribute>();
            //////定时任务(已废除)
            ////services.AddBackgroundServices();
            #endregion
            services.AddHttpClient();

            services.AddControllersWithViews(options =>
            {
                options.Filters.Add <GlobalExceptionFilter>();
                options.Filters.Add <ModelActionFilter>();
                options.ModelMetadataDetailsProviders.Add(new ModelBindingMetadataProvider());
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            }).AddNewtonsoftJson(options =>
            {
                // 返回数据首字母不小写,CamelCasePropertyNamesContractResolver是小写
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });
            services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN");
            services.AddControllersWithViews().AddControllersAsServices();
            //调试前端可更新
            services.AddControllersWithViews().AddRazorRuntimeCompilation();
            services.AddOptions();
            services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(GlobalContext.HostingEnvironment.ContentRootPath + Path.DirectorySeparatorChar + "DataProtection"));
            GlobalContext.SystemConfig  = Configuration.GetSection("SystemConfig").Get <SystemConfig>();
            GlobalContext.Services      = services;
            GlobalContext.Configuration = Configuration;
            //更新数据库管理员和主系统
            try
            {
                var context     = DBContexHelper.Contex();
                var _setService = new Service.SystemOrganize.SystemSetService(context);
                Domain.SystemOrganize.SystemSetEntity temp = new Domain.SystemOrganize.SystemSetEntity();
                temp.F_AdminAccount  = GlobalContext.SystemConfig.SysemUserCode;
                temp.F_AdminPassword = GlobalContext.SystemConfig.SysemUserPwd;
                temp.F_DBProvider    = GlobalContext.SystemConfig.DBProvider;
                temp.F_DbString      = GlobalContext.SystemConfig.DBConnectionString;
                _setService.SubmitForm(temp, GlobalContext.SystemConfig.SysemMasterProject);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex);
            }
        }
 public RedisRateLimitCounterStore(RedisOptions options)
 {
     _options = options;
     _client  = new CSRedisClient(_options.ConnectionString);
 }
Exemplo n.º 5
0
 /// <summary>
 /// 构造函数。
 /// </summary>
 /// <param name="redisClient"></param>
 public CSRedisSessionCache(CSRedisClient redisClient)
 {
     _redisClient = redisClient;
 }
 /// <summary>
 /// Redis 缓存策略
 /// </summary>
 RedisObjectCacheStrategy(CSRedisClient csRedisClient)
 {
     Client = csRedisClient;
 }
Exemplo n.º 7
0
 public RedisHelper(string connection)
 {
     _cache = new CSRedis.CSRedisClient(connection);
 }
Exemplo n.º 8
0
 public RedisHelper()
 {
     redis = new CSRedisClient("127.0.0.1:6379");
 }
Exemplo n.º 9
0
        /// <summary>
        /// 添加RedisSession。
        /// </summary>
        /// <param name="services">服务。</param>
        /// <param name="redisClient">redis客户端。</param>
        /// <param name="configure">Session配置。</param>
        /// <returns></returns>
        public static IServiceCollection AddRedisSession(this IServiceCollection services, CSRedisClient redisClient, Action <SessionOptions> configure = null)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (redisClient == null)
            {
                throw new ArgumentNullException(nameof(redisClient));
            }

            if (configure != null)
            {
                services.Configure(configure);
            }

            services.AddSingleton <IDistributedSessionCache>(new CSRedisSessionCache(redisClient));
            services.TryAddTransient <ISessionStore, DistributedRedisSessionStore>();
            services.AddDataProtection();
            return(services);
        }
Exemplo n.º 10
0
 public RedisCacheCatpcha(CSRedisClient redisClient)
 {
     RedisClient = redisClient;
 }
Exemplo n.º 11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CacheClientRealize"/> class.
 /// </summary>
 /// <param name="redisClient">CSRedis.RedisClient.</param>
 public CacheClientRealize(CSRedisClient redisClient)
 {
     this.redisClient = redisClient;
 }
Exemplo n.º 12
0
        public RedisCacheService()
        {
            var csredis = new CSRedisClient(AppSetting.RedisConnectionString);

            RedisHelper.Initialization(csredis);
        }
Exemplo n.º 13
0
 public static void InitInstance(CSRedisClient client)
 {
     Instance = new RedisContainerCacheStrategy(client);
 }
Exemplo n.º 14
0
 /// <summary>
 /// Redis 缓存策略
 /// </summary>
 private RedisContainerCacheStrategy(CSRedisClient csRedisClient)
 {
     Client            = csRedisClient;
     BaseCacheStrategy = () => RedisObjectCacheStrategy.Instance;
     RegisterCacheStrategyDomain(this);
 }
Exemplo n.º 15
0
 public void CacheRedis()
 {
     var          csredis    = new CSRedisClient("127.0.0.1:6379,password=svse,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=key前辍");
     CSRedisCache redisCache = new CSRedisCache(csredis);
 }
Exemplo n.º 16
0
 public CSRedisHelpers(string conn, int DbNum = 0)
 {
     csredis = CSRedisConnectionHelp.GetConnectionMultiplexer(conn + ",defaultDatabase=" + DbNum);
 }
Exemplo n.º 17
0
 public static RedisObjectCacheStrategy CreateInstance(CSRedisClient csRedisClient)
 {
     return(Instance ??= new RedisObjectCacheStrategy(csRedisClient));
 }
Exemplo n.º 18
0
 public PubMsg()
 {
     csRedisClient = new CSRedis.CSRedisClient("127.0.0.1:6379,password=123,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240");
 }
Exemplo n.º 19
0
 /// <summary>
 /// 构造函数
 /// 注意:请以单例使用
 /// </summary>
 /// <param name="config">配置字符串</param>
 public RedisCache(string config)
 {
     _redisCLient = new CSRedisClient(config);
 }
Exemplo n.º 20
0
        private JobList <T> GetJobsWithProperties <T>(
            [NotNull] CSRedisClient redis,
            [NotNull] string[] jobIds,
            string[] properties,
            string[] stateProperties,
            [NotNull] Func <Job, IReadOnlyList <string>, IReadOnlyList <string>, T> selector)
        {
            if (jobIds == null)
            {
                throw new ArgumentNullException(nameof(jobIds));
            }
            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }

            if (jobIds.Length == 0)
            {
                return(new JobList <T>(new List <KeyValuePair <string, T> >()));
            }

            var jobs   = new Dictionary <string, Task <string[]> >(jobIds.Length, StringComparer.OrdinalIgnoreCase);
            var states = new Dictionary <string, Task <string[]> >(jobIds.Length, StringComparer.OrdinalIgnoreCase);

            properties = properties ?? new string[0];

            var extendedProperties = properties
                                     .Concat(new[] { "Type", "Method", "ParameterTypes", "Arguments" })
                                     .ToArray();

            var tasks = new List <Task>(jobIds.Length * 2);

            foreach (var jobId in jobIds.Distinct())
            {
                var jobTask = redis.HMGetAsync(
                    _storage.GetRedisKey($"job:{jobId}"),
                    extendedProperties);
                tasks.Add(jobTask);
                jobs.Add(jobId, jobTask);

                if (stateProperties != null)
                {
                    var taskStateJob = redis.HMGetAsync(
                        _storage.GetRedisKey($"job:{jobId}:state"),
                        stateProperties);
                    tasks.Add(taskStateJob);
                    states.Add(jobId, taskStateJob);
                }
            }
            Task.WaitAll(tasks.ToArray());

            var jobList = new JobList <T>(jobIds
                                          .Select(jobId => new
            {
                JobId  = jobId,
                Job    = jobs[jobId].Result,
                Method = TryToGetJob(
                    jobs[jobId].Result[properties.Length],
                    jobs[jobId].Result[properties.Length + 1],
                    jobs[jobId].Result[properties.Length + 2],
                    jobs[jobId].Result[properties.Length + 3]),
                State = stateProperties != null ? states[jobId].Result : null
            })
                                          .Select(x => new KeyValuePair <string, T>(
                                                      x.JobId,
                                                      x.Job.Any(y => y != null)
                        ? selector(x.Method, x.Job, x.State)
                        : default(T))));

            return(jobList);
        }
Exemplo n.º 21
0
 public RedisDistSrvProvider()
 {
     _redisClient = new CSRedisClient($"{RedisCache.HostAddress},defaultDatabase=7");
 }
Exemplo n.º 22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            #region 添加Swagger
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "My API", Version = "v1"
                });
                // 获取xml文件名
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                // 获取xml文件路径
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                // 添加控制器层注释,true表示显示控制器注释
                //options.IncludeXmlComments(xmlPath, true);


                #region Jwt
                //开启权限小锁
                options.OperationFilter <AddResponseHeadersFilter>();
                options.OperationFilter <AppendAuthorizeToSummaryOperationFilter>();

                //在header中添加token,传递到后台
                options.OperationFilter <SecurityRequirementsOperationFilter>();
                options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传递)直接在下面框中输入Bearer {token}(注意两者之间是一个空格) \"",
                    Name        = "Authorization",          //jwt默认的参数名称
                    In          = ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = SecuritySchemeType.ApiKey
                });
                #endregion
            });
            #endregion

            #region 添加EFCore
            services.Configure <DBConnectionOption>(Configuration.GetSection("ConnectionStrings"));//注入多个链接
            var sqlConnection = Configuration.GetConnectionString("WriteConnection");
            services.AddDbContext <ApiDBContent>(option => option.UseSqlServer(sqlConnection));

            //读写分离

            //services.AddTransient<DbContext, ApiDBContent>();

            #endregion

            #region 添加jwt认证
            services.Configure <TokenManagement>(Configuration.GetSection("tokenManagement"));
            var token = Configuration.GetSection("tokenManagement").Get <TokenManagement>();

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
                    ValidIssuer      = token.Issuer,
                    ValidAudience    = token.Audience,
                    ValidateIssuer   = false,
                    ValidateAudience = false
                };
            });
            #endregion
            services.Configure <WebSettings>(Configuration.GetSection("WebSettings"));
            #region 依赖注入自定义Service接口
            services.AddDataService();
            //services.AddScoped<IAuthenticateService, AuthenticateService>();
            //services.AddScoped<IUserService, UserService>();
            #endregion

            #region 注入Redis
            // Redis客户端要定义成单例, 不然在大流量并发收数的时候, 会造成redis client来不及释放。另一方面也确认api控制器不是单例模式,
            string redisConnect = Configuration.GetConnectionString("redis");
            var    csredis      = new CSRedisClient(redisConnect);

            RedisHelper.Initialization(csredis);
            services.AddSingleton(csredis);

            services.AddSingleton <IDistributedCache>(new CSRedisCache(new CSRedisClient(redisConnect)));

            // 连接Redis的容器,此时6380端口。
            services.AddSingleton <IDistributedSessionCache>(new CSRedisSessionCache(new CSRedisClient(redisConnect)));
            services.AddRedisSession();

            services.AddScoped(typeof(RedisCoreHelper));
            #endregion

            #region 配置CAP
            services.AddCap(x =>
            {
                x.UseEntityFramework <ApiDBContent>();

                //启用操作面板
                x.UseDashboard();
                //使用RabbitMQ
                x.UseRabbitMQ(rb =>
                {
                    //rabbitmq服务器地址
                    rb.HostName = "localhost";

                    rb.UserName = "******";
                    rb.Password = "******";

                    //指定Topic exchange名称,不指定的话会用默认的
                    rb.ExchangeName = "cap.text.exchange";
                });

                //设置处理成功的数据在数据库中保存的时间(秒),为保证系统新能,数据会定期清理。
                x.SucceedMessageExpiredAfter = 24 * 3600;

                //设置失败重试次数
                x.FailedRetryCount = 5;
            });
            #endregion


            // 如果不实现IDistributedCache将会异常。
            services.AddSession();

            //添加后台运行任务
            services.AddHostedService <BackgroundJob>();

            #region 注入 Quartz调度类
            //注入 Quartz调度类
            services.AddSingleton <QuartzStartup>();
            services.AddTransient <UserInfoSyncjob>();                        // 这里使用瞬时依赖注入
            services.AddSingleton <ISchedulerFactory, StdSchedulerFactory>(); //注册ISchedulerFactory的实例。

            services.AddSingleton <IJobFactory, IOCJobFactory>();
            #endregion
        }
Exemplo n.º 23
0
        private CSRedisClient InitDB(string redisDbConnectionString)
        {
            var redisdb = new CSRedisClient(redisDbConnectionString);

            return(redisdb);
        }
 public CSRedisCache(CSRedisClient redisClient)
 {
     _redisClient = redisClient;
 }
Exemplo n.º 25
0
 public static void CreateDb(this CSRedisClient client)
 {
 }
Exemplo n.º 26
0
 public RedisManage(string connection)
 {
     Client = new CSRedisClient(connection);
 }
Exemplo n.º 27
0
 public DockerService(ILogger <DockerService> logger)
 {
     _logger       = logger;
     cSRedisClient = new CSRedisClient("127.0.0.1:6379,defaultDatabase=10");
     RedisHelper.Initialization(cSRedisClient);
 }
Exemplo n.º 28
0
 /// <summary>
 /// 初始化csredis静态访问类
 /// RedisHelper.Initialization(
 ///		csredis: new CSRedis.CSRedisClient(\"127.0.0.1:6379,pass=123,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=10240,prefix=key前辍\"),
 ///		serialize: value => Newtonsoft.Json.JsonConvert.SerializeObject(value),
 ///		deserialize: (data, type) => Newtonsoft.Json.JsonConvert.DeserializeObject(data, type))
 /// </summary>
 /// <param name="csredis"></param>
 /// <param name="serialize"></param>
 /// <param name="deserialize"></param>
 public static void Initialization(CSRedisClient csredis, Func <object, string> serialize, Func <string, Type, object> deserialize)
 {
     _instance    = csredis;
     _serialize   = serialize;
     _deserialize = deserialize;
 }
Exemplo n.º 29
0
 public static void Initalize()
 {
     Cache    = new CSRedisClient(AppSettings.Configuration["RedisServer:Cache"]);
     Sequence = new CSRedisClient(AppSettings.Configuration["RedisServer:Sequence"]);
     Session  = new CSRedisClient(AppSettings.Configuration["RedisServer:Session"]);
 }
Exemplo n.º 30
0
 public RedisCache(CSRedisClient client)
 {
     _client = client;
 }