static void Main(string[] args) { string server = "localhost:30379"; var secon = ConnectionMultiplexer.Connect(server + ",allowAdmin=true"); var db = secon.GetDatabase(1); var cscon = new CSRedis.CSRedisClient(server); RedisHelper.Initialization(cscon); ThreadPool.SetMinThreads(1000, 1000); Console.WriteLine("---热身---"); secon.GetServer(server).FlushDatabase(1); SERedisTest(db, 1); cscon.NodesServerManager.FlushDb(); CSRedisTest(cscon, 1); // int[] param = { 1 }; int[] param = { 1, 10, 100, 1000, 10000 }; foreach (var loop in param) { Console.WriteLine($"---{loop}---"); secon.GetServer(server).FlushDatabase(1); SERedisTest(db, loop); cscon.NodesServerManager.FlushDb(); CSRedisTest(cscon, loop); } Console.WriteLine("---结束---"); }
public void SentinelInit() { var csredis = new CSRedis.CSRedisClient("mymaster,password=123", new[] { "192.169.1.10:26379", "192.169.1.11:26379", "192.169.1.12:26379" }); csredis.Set("test", DateTime.Now.ToString()); csredis.Get("test"); }
public void OnlyDbInit() { var rds = new CSRedis.CSRedisClient("127.0.0.1:6379,password=123,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240"); RedisHelper.Initialization(rds); RedisHelper.Set("test", DateTime.Now.ToString()); RedisHelper.Get("test"); }
static void test_cs(out CSRedisClient rds) { rds = new CSRedis.CSRedisClient("127.0.0.1:6379,password=lead-it_rds"); // var sub1 = redis.SubscribeList("web", msg => Console.WriteLine($"sub1 -> list1 : {msg}")); var sub6 = rds.Subscribe(("web", msg => Rcv(msg.Body, msg.Channel))); rds.PublishAsync("web", $"add at{DateTime.Now}"); }
public void ClusterDbInit() { var csredis = new CSRedis.CSRedisClient(null, "127.0.0.1:6371,password=123,defaultDatabase=11,poolsize=10,ssl=false,writeBuffer=10240", "127.0.0.1:6372,password=123,defaultDatabase=12,poolsize=11,ssl=false,writeBuffer=10240", "127.0.0.1:6373,password=123,defaultDatabase=13,poolsize=12,ssl=false,writeBuffer=10240", "127.0.0.1:6374,password=123,defaultDatabase=14,poolsize=13,ssl=false,writeBuffer=10240"); csredis.Set("test", DateTime.Now.ToString()); csredis.Get("test"); }
public CSRedisClient ClusterRedis() { var csredis = new CSRedis.CSRedisClient(null, "127.0.0.1:6371,password=123,defaultDatabase=11,poolsize=10,ssl=false,writeBuffer=10240,prefix=key前辍", "127.0.0.1:6372,password=123,defaultDatabase=12,poolsize=11,ssl=false,writeBuffer=10240,prefix=key前辍", "127.0.0.1:6373,password=123,defaultDatabase=13,poolsize=12,ssl=false,writeBuffer=10240,prefix=key前辍", "127.0.0.1:6374,password=123,defaultDatabase=14,poolsize=13,ssl=false,writeBuffer=10240,prefix=key前辍"); //实现思路:根据key.GetHashCode() % 节点总数量,确定连向的节点 //也可以自定义规则(第一个参数设置) return(csredis); }
public RedisClient(string name) { if (!client.TryGetValue(name, out var redis)) { _redis = new CSRedisClient(name); client.TryAdd(name, _redis); } else { _redis = redis; } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); services.AddSignalR() .AddRedis(Configuration["Redis:Url"], options => options.Configuration.ChannelPrefix = "ChatApp") .AddJsonProtocol(options => options.PayloadSerializerOptions.PropertyNamingPolicy = null); var client = new CSRedis.CSRedisClient(Configuration["Redis:Url"]); services.AddSingleton(typeof(CSRedisClient), client); }
//need Caching.CSRedis public static void AddRedisCaches(this IServiceCollection services, IConfiguration configuration) { string redisServer = configuration.GetValue <string>("RedisServer:Server"); var csredis = new CSRedis.CSRedisClient(redisServer); RedisHelper.Initialization(csredis); if (RedisHelper.Instance == null) { throw new Exception("redis config not fund"); } services.AddSingleton <IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance)); services.AddSingleton <ICacheProvider, RedisCacheProvider>(); }
static BusinessMember2() { var con = Startup.appSettings.GetSection("Redis").GetSection("ConnectionString").Value; System.Console.WriteLine($"Redis={con}"); var csredis = new CSRedis.CSRedisClient(con); RedisHelper.Initialization(csredis); RedisHelper.HSetAsync("Role", "value", "111"); RedisHelper.HSetAsync("Role", "value2", "222"); RedisHelper.HSetAsync("Role", "value3", "333"); var values = RedisHelper.HGetAll("Role"); }
static void Main(string[] args) { CSRedisClient redisClient = new CSRedis.CSRedisClient("127.0.0.1:6379,defaultDatabase=0"); var lockKey = "lockKey"; var stockKey = "stock"; redisClient.Set(stockKey, 5); //商品库存 var releaseLockScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; //释放锁的redis脚本 redisClient.Del(lockKey); //测试前,先把锁删了. Parallel.For(0, 10, i => { var id = Guid.NewGuid().ToString("N"); //获取锁 do { //set : key存在则失败,不存在才会成功,并且过期时间5秒 var success = redisClient.Set(lockKey, id, expireSeconds: 5, exists: RedisExistence.Nx); if (success == true) { break; } Thread.Sleep(TimeSpan.FromSeconds(1));//休息1秒再尝试获取锁 } while (true); Console.WriteLine($"线程:{Task.CurrentId} 拿到了锁,开始消费"); //扣减库存 var currentStock = redisClient.IncrBy(stockKey, -1); if (currentStock < 0) { Console.WriteLine($"库存不足,线程:{Task.CurrentId} 抢购失败!"); redisClient.Eval(releaseLockScript, lockKey, id); return; } //模拟处理业务,这里不考虑失败的情况 Thread.Sleep(TimeSpan.FromSeconds(new Random().Next(1, 3))); Console.WriteLine($"线程:{Task.CurrentId} 消费完毕!剩余 {currentStock} 个"); //业务处理完后,释放锁. redisClient.Eval(releaseLockScript, lockKey, id); }); }
public void Initialization() { redisClients = new CSRedisClient[this._configs.Count]; //定义成单例 int i = 0; foreach (var item in this._configs) { //string key = $"{item.C_IP}:{item.C_Post}/{item.C_Defaultdatabase}"; string key = $"{i}"; //var connectionString = $"{item.C_IP}:{item.C_Post},password={item.C_Password},defaultDatabase={item.C_Defaultdatabase},poolsize={item.C_PoolSize}," + // $"preheat=true,ssl=false,writeBuffer=10240,prefix={item.C_Prefix}"; var connectionString = $"{item.C_IP}:{item.C_Post},password={item.C_Password},defaultDatabase={item.C_Defaultdatabase},poolsize={item.C_PoolSize}," + $"preheat=true,ssl=false,writeBuffer=10240"; RedisHas[key] = new CSRedis.CSRedisClient(connectionString); redisClients[i] = new CSRedis.CSRedisClient(connectionString); i++; } }
public InRedisCache(AhphOcelotConfiguration options) { _options = options; CSRedisClient csRedis; if (options.RedisConnectionStrings.Count == 1) { // 普通模式 csRedis = new CSRedisClient(options.RedisConnectionStrings[0]); } else { // 集群模式 //实现思路:根据key.GetHashCode() % 节点总数量,确定连向的节点 //也可以自定义规则(第一个参数设置) csRedis = new CSRedis.CSRedisClient(null, options.RedisConnectionStrings.ToArray()); } // Init RedisHelper RedisHelper.Initialization(csRedis); }
public static void RedisQueue() { var rds = new CSRedis.CSRedisClient("10.0.0.236:6388,password=nanjing123,defaultDatabase=6,poolsize=50"); RedisHelper.Initialization(rds); //普通订阅 rds.Subscribe( ("topic_ctrlMsg", msg => Console.WriteLine("1|" + msg.Body)) ); rds.Subscribe( ("topic_ctrlMsg", msg => Console.WriteLine("2|" + msg.Body)) ); for (int i = 0; i < 10; i++) { rds.Publish("topic_ctrlMsg", "{'a':100}"); Thread.Sleep(5000); } }
public MenuController(IMenuBLL menuBLL) { _menuBLL = menuBLL; _client = new CSRedis.CSRedisClient("127.0.0.1:6379"); RedisHelper.Initialization(_client); }
internal CSRedisClientPipeTransaction(CSRedisClient csredis) : base(csredis) { }
private CSRedisClientPipeTransaction(CSRedisClient csredis, ConcurrentDictionary <string, (List <int> indexes, Object <RedisClient> conn)> conns,
public CustomerRedis() { CSRedisClient csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,defaultDatabase=1,poolsize=50,ssl=false,writeBuffer=10240"); RedisHelper.Initialization(csredis); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { CSRedisClient csredis = new CSRedis.CSRedisClient(Configuration.GetSection("RedisConnectionString")["Default"]); //var connection = @"Server=.;Database=Note;UID=sa;PWD=12345678;"; services.AddDbContext <NoteContext>(options => { //options.UseSqlServer(connection) options.UseSqlServer(Configuration.GetConnectionString("Default")); }); services.AddIdentity <NoteUser, IdentityRole>() .AddEntityFrameworkStores <NoteContext>() .AddDefaultTokenProviders(); services.Configure <IdentityOptions>(options => { options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; //options.Cookies.ApplicationCookie.LoginPath = new PathString("/Account/Login"); }); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = new PathString("/Home/Index"); options.ExpireTimeSpan = TimeSpan.FromMinutes(60); options.Cookie.Name = "CookieName"; }); services.AddControllersWithViews(); services.AddMvc(option => { option.Filters.Add(typeof(GlobalExceptionFilter)); }); //允许所有跨域 services.AddCors(options => options.AddPolicy("cors", policy => { policy .SetIsOriginAllowed(x => true) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); })); services.AddMvc(option => option.EnableEndpointRouting = false); //允许一个或多个来源可以跨域 // services.AddCors(options => // { // options.AddPolicy("CustomCorsPolicy", policy =>{ // // 设定允许跨域的来源,有多个可以用','隔开 // policy.WithOrigins("http://localhost:8081","http://localhost:8082") // .AllowAnyHeader() // .AllowAnyMethod() // .AllowCredentials(); // }); // }); services.AddHttpClient(); services.AddAutoMapper(typeof(AutoMapperConfigs)); // services.AddScoped<INoteRepository, NoteRepository>(); // services.AddScoped<INoteTypeRepository, NoteTypeRepository>(); //services.AddSingleton(typeof(IDistributedLockFactory), lockFactory); // services.AddScoped(typeof(ProductService)); services.AddSingleton <IDistributedCache>(new CSRedisCache(csredis)); //services.AddScoped<IResdisClient, CustomerRedis>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddControllersAsServices(); #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.Scan(scan => //{ // Assembly assemblysServices = Assembly.Load("Application"); // scan.FromAssemblies(assemblysServices) // .AddClasses(classes => classes.Where(t => t.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase))) // .AsImplementedInterfaces() // .AsSelf() // .WithScopedLifetime(); //}); //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); //redis集群 var csredis = new CSRedis.CSRedisClient(null, "127.0.0.1:6379,password=123456,defaultDatabase=0", "127.0.0.1:6379,password=123456,defaultDatabase=1", "127.0.0.1:6379,password=123456,defaultDatabase=2", "127.0.0.1:6379,password=123456,defaultDatabase=3"); 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 }
/// <summary> /// 初始化Redis服务 /// </summary> public static void Initialization() { var csredis = new CSRedis.CSRedisClient(ConfigsHelper.GetRedisCacheConnectionString()); RedisHelper.Initialization(csredis); }
// Start is called before the first frame update void Start() { CSRedis = new CSRedis.CSRedisClient("127.0.0.1:6379"); RedisHelper.Initialization(CSRedis); }
// 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.AddTransient <IUserRoleRepository, UserRoleRepository>(); services.AddTransient <IRoleRepository, RoleRepository>(); services.AddTransient <IUserRepository, UserRepository>(); services.AddTransient <IDataCaches <User>, DataCaches <User> >(); services.AddTransient <IDataCaches <Role>, DataCaches <Role> >(); services.AddTransient <IDataCaches <UserRole>, DataCaches <UserRole> >(); services.AddTransient <IExceptionLogger, ExceptionLogger>(); services.AddSingleton <IRabitMQHandler, RabitMQHandler>(); //MQ独立实例内部维护连接池 services.AddSingleton <IDataRepository, DataRepository>(); //MySQL独立实例内部维护连接池 //redis分布式缓存支持 var csredis = new CSRedis.CSRedisClient(Configuration["Redis:Configuration"]); RedisHelper.Initialization(csredis); services.AddSingleton <IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));//Redis独立实例内部维护连接池 var secretKey = Configuration["JWTAuth:secretKey"]; var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)); //服务接口JWT Bearer验证配置 //用法: //JS:headers:{"Authorization": "Bearer "+token}, //客户端:URL?access_token=token services.AddAuthentication(options => { //TOKEN //不使用COOKIE // Identity made Cookie authentication the default. // However, we want JWT Bearer Auth to be the default. options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { // Configure JWT Bearer Auth to expect our security key options.TokenValidationParameters = new TokenValidationParameters { LifetimeValidator = (before, expires, token, param) => { var res = expires > DateTime.UtcNow; return(res); }, ValidateIssuer = true, //是否验证Issuer ValidateAudience = true, //是否验证Audience ValidateLifetime = true, //是否验证失效时间 ValidateIssuerSigningKey = true, //是否验证SecurityKey*/ ValidIssuer = Configuration["JWTAuth:issuer"], ValidAudience = Configuration["JWTAuth:audience"], IssuerSigningKey = signingKey }; // We have to hook the OnMessageReceived event in order to // allow the JWT authentication handler to read the access // token from the query string when a WebSocket or // Server-Sent Events request comes in. options.Events = new JwtBearerEvents { // Change to use Name as the user identifier for SignalR // WARNING: This requires that the source of your JWT token // ensures that the Name claim is unique! // If the Name claim isn't unique, users could receive messages // intended for a different user! //signalR认证 OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; if (!string.IsNullOrEmpty(accessToken)) { context.Token = accessToken; } return(Task.CompletedTask); } }; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSignalR(); //跨域支持 services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder.AllowAnyOrigin(); builder.AllowAnyMethod(); builder.AllowAnyHeader(); }); }); //services.AddSingleton<IUserIdProvider, NameUserIdProvider>(); }