Exemple #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add <ErrorHandler>();//添加全局捕获异常
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //依赖注入
            DependencyInjection.Initialize(services);

            // Entity Framework Contexts
            var ownDbCon = _appConfigurations.DefaultConnection;

            services.AddDbContext <TestDbcontext>(options => options.UseSqlServer(ownDbCon));

            //add session support 验证码
            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromMinutes(20);
                options.Cookie.HttpOnly = true;
            });

            var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,password=,defaultDatabase=2,poolsize=10,ssl=false,writeBuffer=10240,prefix=keyTest_");

            RedisHelper.Initialization(csredis);

            //注册MVC分布式缓存
            services.AddSingleton <IDistributedCache>(new CSRedisCache(RedisHelper.Instance));

            //微信
            services.AddSenparcGlobalServices(Configuration) //Senparc.CO2NET 全局注册
            .AddSenparcWeixinServices(Configuration);        //Senparc.Weixin 注册
        }
Exemple #2
0
        static void HASHTEST0()
        {
            Console.WriteLine("HashMap,管道,先整理好所有KEYVALUE,再一次性写入");
            Console.WriteLine("请输入写入次数:");
            var count = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} Redis 开始整理。。。");
            var rds = new CSRedis.CSRedisClient("127.0.0.1:6379,defaultDatabase=1,poolsize=100,ssl=false,writeBuffer=1024000");

            var stw = Stopwatch.StartNew();

            var vals = new List <object>();

            for (int i = 0; i < count; i++)
            {
                vals.Add(Guid.NewGuid().ToString());
                vals.Add(i);
            }

            stw.Stop();
            Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} Redis 整理完成,耗时{stw.Elapsed.TotalMilliseconds} 毫秒。。。");

            stw.Restart();
            Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} Redis 开始写入。。。");

            rds.StartPipe(p => rds.HMSet("asdfghj3kl1", vals.ToArray()));

            stw.Stop();
            Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} Redis {count} 次写入完成,耗时{stw.Elapsed.TotalMilliseconds} 毫秒");
        }
        public static IServiceCollection AddCsRedis(this IServiceCollection services, RedisCacheOption option)
        {
            services.AddSingleton(option);
            List <string> csredisConns = new List <string>();
            string        password     = option.Password;
            int           defaultDb    = option.Database;
            string        ssl          = option.SslHost;
            string        keyPrefix    = option.DefaultCustomKey;
            int           writeBuffer  = 10240;
            int           poolsize     = 10;

            foreach (var e in option.Endpoints)
            {
                string server = e.Host;
                int    port   = e.Port;
                if (string.IsNullOrWhiteSpace(server) || port <= 0)
                {
                    continue;
                }
                csredisConns.Add($"{server}:{port},password={password},defaultDatabase={defaultDb},poolsize={poolsize},ssl={ssl},writeBuffer={writeBuffer},prefix={keyPrefix}");
            }
            var csredis = new CSRedis.CSRedisClient(null, csredisConns.ToArray());

            RedisHelper.Initialization(csredis);
            services.AddScoped <IRedisManager, CsRedisManager>();
            return(services);
        }
        public RedisFetchedJob(
            [NotNull] RedisStorage storage,
            [NotNull] CSRedis.CSRedisClient redisClient,
            [NotNull] string jobId,
            [NotNull] string queue)
        {
            if (storage == null)
            {
                throw new ArgumentNullException(nameof(storage));
            }
            if (redisClient == null)
            {
                throw new ArgumentNullException(nameof(redisClient));
            }
            if (jobId == null)
            {
                throw new ArgumentNullException(nameof(jobId));
            }
            if (queue == null)
            {
                throw new ArgumentNullException(nameof(queue));
            }

            _storage     = storage;
            _redisClient = redisClient;
            JobId        = jobId;
            Queue        = queue;
        }
Exemple #5
0
        public void Init()
        {
            List <string> csredisConns = new List <string>();
            string        password     = "******";
            int           defaultDb    = 0;
            string        ssl          = "";
            string        keyPrefix    = "";
            int           writeBuffer  = 10240;
            int           poolsize     = 20;
            int           timeout      = 10;

            csredisConns.Add($"198.185.15.16:6379,password={password},defaultDatabase={defaultDb},poolsize={poolsize},ssl={ssl},writeBuffer={writeBuffer},prefix={keyPrefix},preheat={1},idleTimeout={timeout},testcluster={true}");

            CSRedis.CSRedisClient csredis;

            try
            {
                csredis = new CSRedis.CSRedisClient(null, csredisConns.ToArray());
            }
            catch (Exception ex)
            {
                throw new ArgumentException($"请检查是否为非密码模式,Password必须为空字符串;请检查Database是否为0,只能在非集群模式下才可配置Database大于0;{ex}");
            }

            RedisHelper.Initialization(csredis);

            _redisDatabase = new CsRedisManager(new RedisCacheOption
            {
            }, new NetPro.CsRedis.SystemTextJsonSerializer());
        }
        /// <summary>
        /// 添加Ip限流
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <param name="cacheConfig"></param>
        public static void AddIpRateLimit(this IServiceCollection services, IConfiguration configuration, CacheConfig cacheConfig)
        {
            #region IP限流

            services.Configure <IpRateLimitOptions>(configuration.GetSection("IpRateLimiting"));
            services.Configure <IpRateLimitPolicies>(configuration.GetSection("IpRateLimitPolicies"));

            if (cacheConfig.TypeRateLimit == Common.Cache.CacheType.Redis)
            {
                //redis
                var redisRateLimit = new CSRedis.CSRedisClient(cacheConfig.Redis.ConnectionStringRateLimit);
                services.AddSingleton <IDistributedCache>(new CSRedisCache(redisRateLimit));
                services.AddSingleton <IIpPolicyStore, DistributedCacheIpPolicyStore>();
                services.AddSingleton <IRateLimitCounterStore, DistributedCacheRateLimitCounterStore>();
            }
            else
            {
                //内存
                services.AddMemoryCache();
                services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>();
                services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
            }
            services.AddSingleton <IRateLimitConfiguration, RateLimitConfiguration>();

            #endregion IP限流
        }
Exemple #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            var csredis = new CSRedis.CSRedisClient("192.168.1.111:6379,password=bl123456,defaultDatabase=0,poolsize=500,ssl=false");

            RedisHelper.Initialization(csredis);
        }
Exemple #8
0
        static void ZSetWriteTest()
        {
            Console.WriteLine("ZSet 写入测试");
            Console.WriteLine("请输入DB:");
            var db = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("请输入KEY:");
            var key = Console.ReadLine();

            Console.WriteLine("请输入开始值:");
            var start = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("请输入结束值:");
            var end = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} Redis 开始整理。。。");
            var rds = new CSRedis.CSRedisClient(null, $"127.0.0.1:6379,defaultDatabase={db},poolsize=100,ssl=false,writeBuffer=102400");


            var stw = Stopwatch.StartNew();

            var vals = new List <(double, object)>();

            for (int i = start; i < end; i++)
            {
                vals.Add((i * 10, $"{key}_{i}"));
            }

            stw.Stop();
            Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} Redis 整理完成,耗时{stw.Elapsed.TotalMilliseconds} 毫秒。。。");

            var page_size  = 500000;
            var page_index = 0;
            var total_page = Convert.ToInt32(vals.Count / page_size) + (vals.Count % page_size > 0 ? 1 : 0);

            var stw01 = Stopwatch.StartNew();

            do
            {
                stw.Restart();
                Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} Redis Page {page_index} 开始提取。。。");

                var temp_vals = vals.Skip(page_index * page_size).Take(page_size);

                stw.Stop();
                Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} Redis Page {page_index} 提取耗时 {stw.ElapsedMilliseconds} 毫秒。。。");

                stw.Restart();
                Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} Redis Page {page_index} 开始写入。。。");
                rds.StartPipe(p => rds.ZAdd(key, temp_vals.ToArray()));
                stw.Stop();
                Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} Redis Page {page_index} 写入完成,耗时 {stw.ElapsedMilliseconds} 毫秒。。。");

                page_index++;
            } while (total_page > page_index);


            stw01.Stop();
            Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} Redis {end - start} 次写入完成,耗时{stw01.Elapsed.TotalMilliseconds} 毫秒");
        }
Exemple #9
0
        public static void Main(string[] args)
        {
            string envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            if (String.IsNullOrWhiteSpace(envName))
            {
                throw new ArgumentNullException("EnvironmentName not found in ASPNETCORE_ENVIRONMENT");
            }

            var appconfig = new ConfigurationBuilder()
                            .SetBasePath(Path.Combine(AppContext.BaseDirectory))
                            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                            .AddJsonFile($"appsettings.{envName}.json", optional: true)
                            .Build();
            var host = new WebHostBuilder()
                       .UseEnvironment(envName)
                       .UseConfiguration(appconfig)
                       .UseKestrel()
                       .UseUrls(appconfig.GetValue <string>("WebHostBuilder:UseUrls"))
                       .UseNLog()
                       .UseStartup <Startup>();

            var csredis = new CSRedis.CSRedisClient(appconfig.GetValue <string>("CSRedis:Client"));

            RedisHelper.Initialization(csredis);

            host.Build().Run();
            //CreateWebHostBuilder(args).Build().Run();
        }
Exemple #10
0
        public void AddServices(IServiceCollection services)
        {
            services.AddSingleton <RedisOptions>();
            var csredis = new CSRedis.CSRedisClient(redisOptions.RedisConnectString);

            RedisHelper.Initialization(csredis);
            services.AddScoped <IMQTransRedis, CSRedisService>();
        }
Exemple #11
0
        /// <summary>
        /// 注册 AopCache ,默认 自己传入实现缓存类,替换默认的MemoryCache
        /// </summary>
        /// <param name="services"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static void AddAopCacheUseCsRedisWithMessagePack(this IServiceCollection services, string connectionString)
        {
            var csredis = new CSRedis.CSRedisClient(connectionString);

            RedisHelper.Initialization(csredis);
            services.AddSingleton <IAopCacheProvider, RedisCacheWithMessagePackProvider>();
            services.ConfigureDynamicProxy();
        }
Exemple #12
0
        public CacheDb(RedisConnConfig config)
        {
            string str = $"{config.conn}:{config.port},password={config.password},defaultDatabase={config.database},poolsize={config.poolsize},ssl={config.isSSL},writeBuffer={config.writeBuffer},prefix={config.prefix}";

            var csredis = new CSRedis.CSRedisClient(str);

            Initialization(csredis);
        }
        public ShopCarController(IGoodsList goodsList)
        {
            redis = new CSRedis.CSRedisClient("127.0.0.1:6379");

            RedisHelper.Initialization(redis);

            _goodsList = goodsList;
        }
Exemple #14
0
        public static IServiceCollection AddCsRedis(this IServiceCollection services, IConfiguration configuration)
        {
            var csredis = new CSRedis.CSRedisClient(configuration.GetConnectionString("csredis"));

            RedisHelper.Initialization(csredis);
            //services.AddSingleton<IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
            return(services);
        }
Exemple #15
0
        /// <summary>
        /// 注入方法,读取config文件
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            var csredis = new CSRedis.CSRedisClient(Configuration["ConnectionStrings:Redis"]);

            //初始化 RedisHelper
            RedisHelper.Initialization(csredis);
        }
 private void Commit(CSRedis.CSRedisClient redis, Action <RedisWriteOnlyTransaction> action)
 {
     using (var transaction = new RedisWriteOnlyTransaction(_storage))
     {
         action(transaction);
         transaction.Commit();
     }
 }
Exemple #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,password=123456,defaultDatabase=50");

            RedisHelper.Initialization(csredis);

            services.AddControllers();
        }
Exemple #18
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddMvc()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
            services.Configure <RequestLocalizationOptions>(opts =>
            {
                var supportedCultures = new List <CultureInfo> {
                    new CultureInfo("en-US"),
                    new CultureInfo("zh-CN")
                };
                opts.SupportedCultures       = supportedCultures;
                opts.SupportedUICultures     = supportedCultures;
                opts.RequestCultureProviders = new List <IRequestCultureProvider> {
                    new X_DOVERequestCultureProvider()
                };
            });
            services.AddSession(options => options.IdleTimeout = TimeSpan.FromMinutes(30));

            services.AddResponseCompression();
            services.AddHangfire(config =>
            {
                config.UseStorage(new MySqlStorage("Server=39.104.53.29; uid = zaranet; pwd = 123456; database = amusinghoS;AllowUserVariables=True;    "));
            });
            //注入工作单元
            services.AddDbContext <amusinghoSDbContext>(options => options.UseMySql(DESEncryptHelper.Decrypt(
                                                                                        "wHMoKdCHCsMzxDTTN9+KOGSDC4JDdwxpukgfD+OGDS6W10AAz9lZac3QctGhAr+o1KGJbkuCLwdT4DXj/EM6eLnLKeVRATxDh21b0Jumpb8="
                                                                                        , "12345678")));
            services.AddTransient(typeof(UnitOfWork));
            services.AddScoped <IRedisClient, CustomerRedis>();
            var csredis = new CSRedis.CSRedisClient("39.104.53.29:6379,password=zaranet");

            RedisHelper.Initialization(csredis);

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddControllersWithViews();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => {
                options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
            }).AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options => {
                options.SignInScheme         = CookieAuthenticationDefaults.AuthenticationScheme;
                options.Authority            = "http://localhost:5000";
                options.RequireHttpsMetadata = false;
                options.ClientId             = "mvc client";
                options.ClientSecret         = "mvc secret";
                options.SaveTokens           = true;
                options.ResponseType         = "code";
                options.Scope.Clear();
                options.Scope.Add(OidcConstants.StandardScopes.OpenId);
                options.Scope.Add(OidcConstants.StandardScopes.Profile);
            });
        }
Exemple #19
0
        private static List <string> GetRedisList(C_Sports_Order_Running order, int max)
        {
            CSRedis.CSRedisClient db = null;
            string key      = string.Empty;
            string gameCode = order.GameCode.ToUpper();

            if (gameCode == "CTZQ" || gameCode == "OZB" || gameCode == "SJB")
            {
                key = string.Format("{0}_{1}_{2}_{3}", order.GameCode, order.GameType, RedisKeys.Key_Running_Order_List, order.IssuseNumber);
                db  = RedisHelperEx.DB_Running_Order_CTZQ;
            }
            else if (new string[] { "SSQ", "DLT", "FC3D", "PL3" }.Contains(gameCode))
            {
                key = string.Format("{0}_{1}_{2}", order.GameCode, RedisKeys.Key_Running_Order_List, order.IssuseNumber);
                db  = RedisHelperEx.DB_Running_Order_SCZ_DP;
            }
            if (new string[] { "CQSSC", "JX11X5", "SD11X5", "GD11X5", "GDKLSF", "JSKS", "SDKLPK3" }.Contains(gameCode))
            {
                key = string.Format("{0}_{1}_{2}", order.GameCode, RedisKeys.Key_Running_Order_List, order.IssuseNumber);
                db  = RedisHelperEx.DB_Running_Order_SCZ_GP;
            }
            if (gameCode == "BJDC")
            {
                key = string.Format("{0}_{1}_{2}", "BJDC", RedisKeys.Key_Running_Order_List, order.IssuseNumber);
                db  = RedisHelperEx.DB_Running_Order_BJDC;
            }
            if (gameCode == "JCZQ" || gameCode == "JCLQ")
            {
                var fullKeyNew = string.Format("{0}_{1}", gameCode, RedisKeys.Key_Running_Order_List);
                db = RedisHelperEx.DB_Running_Order_JC;
            }
            if (db != null && !string.IsNullOrEmpty(key))
            {
                var orderInfoList = new List <string>();
                if (gameCode == "JCZQ" || gameCode == "JCLQ")
                {
                    for (int i = 0; i < max; i++)
                    {
                        var fullKey = $"{key}_{i}";
                        var list    = db.LRange(fullKey, 0, -1);
                        if (list.Length > 0)
                        {
                            orderInfoList.AddRange(list);
                        }
                    }
                    return(orderInfoList);
                }
                else
                {
                    var list = db.LRange(key, 0, -1);
                    orderInfoList.AddRange(list);
                    return(orderInfoList);
                }
            }
            return(null);
        }
Exemple #20
0
        /// <summary>
        /// 构建mq服务配置
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configurationRoot"></param>
        public CSRedisBuild(IServiceCollection services, IConfiguration configurationRoot)
        {
            var redisConnOption = services.BuildServiceProvider().GetRequiredService <IOptions <CacheConnOption> >();

            var csredis = new CSRedis.CSRedisClient(redisConnOption?.Value?.ConnectionString);

            RedisHelper.Initialization(csredis);
            services.TryAddSingleton <IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));
            services.TryAddSingleton <ICacheHelper, CacheHelper>();
        }
Exemple #21
0
        public IActionResult Index()
        {
            var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,defaultDatabase=1,poolsize=50,ssl=false,writeBuffer=10240");

            //初始化 RedisHelper
            RedisHelper.Initialization(csredis);
            var list = RedisHelper.LRange("video", 0, 200);

            return(View(list));
        }
Exemple #22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApiDbContext>(options =>
                                                 options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));

            var csredis = new CSRedis.CSRedisClient(Configuration["RedisConnection"]);

            RedisHelper.Initialization(csredis);

            services.AddHostedService <PopulateTaskHostedService>();
        }
Exemple #23
0
        /// <summary>
        /// 使用CSRedis 作为hangfire存储
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="redisClient"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IGlobalConfiguration <RedisStorage> UseRedisStorage(
            [NotNull] this IGlobalConfiguration configuration, CSRedis.CSRedisClient redisClient, RedisStorageOptions options = null)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            var storage = new RedisStorage(redisClient, options);

            return(configuration.UseStorage(storage));
        }
Exemple #24
0
        public void ConfigureServices(IServiceCollection services)
        {
            var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379");

            RedisHelper.Initialization(csredis);

            services.AddSingleton <ITaskServices, TaskServices>();
            services.AddHostedService <SubscribeTaskBgTask>();

            services.AddControllers();
        }
Exemple #25
0
        public RedisBase()
        {
            //连接哨兵
            //var csredis = new CSRedis.CSRedisClient("redis-master", new[] { "127.0.0.1:27000" });
            var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379");

            //var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,password=YourPassword");
            //RedisHelper.Initialization(csredis);
            //初始化 RedisHelper
            RedisHelper.Initialization(csredis);
        }
Exemple #26
0
        public static Dictionary <string, string> GetValuesMap(this CSRedis.CSRedisClient redis, string[] keys)
        {
            var valuesArr = redis.MGet(keys);
            Dictionary <string, string> result = new Dictionary <string, string>(valuesArr.Length);

            for (int i = 0; i < valuesArr.Length; i++)
            {
                result.Add(keys[i], valuesArr[i]);
            }
            return(result);
        }
        public IServiceProvider 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 => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            var connection = Configuration.GetConnectionString("DefaultSqlServer");

            services.AddDbContext <MessageManagementContext>(options => options.UseSqlServer(connection), ServiceLifetime.Transient);
            //注入服务
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSignalR();
            //初始化Redis
            var csredis = new CSRedis.CSRedisClient(Configuration.GetSection("RedisConnectionStrins")["DefaultRedis"]);

            RedisHelper.Initialization(csredis);
            services.AddControllers();
            services.AddAutoMapper();
            services.AddRazorPages();
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddAntiforgery(options =>
            {
                options.FormFieldName = "AntiforgeryFieldname";
                options.HeaderName    = "X-CSRF-TOKEN-Header";
                options.SuppressXFrameOptionsHeader = false;
            });
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath      = "/Admin/Account/Index";
                options.LogoutPath     = "/Admin/Account/Logout";
                options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
            });
            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromMinutes(15);
                options.Cookie.HttpOnly = true;
            });
            var builder = new ContainerBuilder();

            builder.Populate(services);
            //注册服务并实现接口
            builder.RegisterAssemblyTypes(typeof(MenuRepository).Assembly).Where(x => x.Name.EndsWith("Repository")).AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(typeof(MenuService).Assembly).Where(x => x.Name.EndsWith("Service")).AsImplementedInterfaces();
            return(new AutofacServiceProvider(builder.Build()));
        }
Exemple #28
0
        static void Main(string[] args)
        {
            //普通模式
            var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,pass=123456,defaultDatabase=1,poolsize=50,ssl=false,writeBuffer=10240");

            //初始化 RedisHelper
            RedisHelper.Initialization(csredis);
            //Install-Package Caching.CSRedis (本篇不需要)
            //注册mvc分布式缓存
            //services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));
            Test();
            Console.ReadKey();
        }
Exemple #29
0
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            context.Services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = AppSettings.Caching.RedisConnectionString;
            });

            var csredis = new CSRedis.CSRedisClient(AppSettings.Caching.RedisConnectionString);

            RedisHelper.Initialization(csredis);

            context.Services.AddSingleton <IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
        }
Exemple #30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <param name="redisCacheOption"></param>
        /// <returns></returns>
        public static IServiceCollection AddCsRedis(this IServiceCollection services, Func <IServiceProvider, RedisCacheOption> redisCacheOption)
        {
            services.AddSingleton(redisCacheOption);
            var option = redisCacheOption.Invoke(services.BuildServiceProvider());

            services.AddSingleton(option);
            List <string> csredisConns = new List <string>();
            string        password     = option.Password;
            int           defaultDb    = option.Database;
            string        ssl          = option.SslHost;
            string        keyPrefix    = option.DefaultCustomKey;
            int           writeBuffer  = 10240;
            int           poolsize     = option.PoolSize == 0 ? 10 : option.PoolSize;
            int           timeout      = option.ConnectionTimeout;

            foreach (var e in option.Endpoints)
            {
                string server = e.Host;
                int    port   = e.Port;
                if (string.IsNullOrWhiteSpace(server) || port <= 0)
                {
                    continue;
                }
                csredisConns.Add($"{server}:{port},password={password},defaultDatabase={defaultDb},poolsize={poolsize},ssl={ssl},writeBuffer={writeBuffer},prefix={keyPrefix},preheat={option.Preheat},idleTimeout={timeout},testcluster={option.Cluster}");
            }

            CSRedis.CSRedisClient csredis;

            try
            {
                csredis = new CSRedis.CSRedisClient(null, csredisConns.ToArray());
            }
            catch (Exception ex)
            {
                throw new ArgumentException($"请检查是否为非密码模式,Password必须为空字符串;请检查Database是否为0,只能在非集群模式下才可配置Database大于0;{ex}");
            }

            RedisHelper.Initialization(csredis);
            if (option?.Enabled ?? false)
            {
                services.AddSingleton <IRedisManager, CsRedisManager>();
            }
            else
            {
                var _logger = services.BuildServiceProvider().GetRequiredService <ILogger <CsRedisManager> >();
                _logger.LogInformation($"Redis已关闭,当前驱动为NullCache!!!");
                services.AddSingleton <IRedisManager, NullCache>();
            }

            return(services);
        }