记CSRedisCore在NetCore中使用 入门篇封装
首先 Nuget CSRedisCore
新建一个 IRedisClient 接口
1 public interface IRedisClient 2 { 3 string Get(string key); 4 Task<string> GetAsync(string key); 5 void Set(string key, object t, int expiresSec = 0); 6 Task SetAsync(string key, object t, int expiresSec = 0); 7 T Get<T>(string key) where T : new(); 8 Task<T> GetAsync<T>(string key) where T : new(); 9 }
实现接口
1 public class CustomerRedis : IRedisClient 2 { 3 public string Get(string key) 4 { 5 return RedisHelper.Get(key); 6 } 7 8 public T Get<T>(string key) where T : new() 9 { 10 return RedisHelper.Get<T>(key); 11 } 12 13 public async Task<string> GetAsync(string key) 14 { 15 return await RedisHelper.GetAsync(key); 16 } 17 18 public async Task<T> GetAsync<T>(string key) where T : new() 19 { 20 return await RedisHelper.GetAsync<T>(key); 21 } 22 23 public void Set(string key, object t, int expiresSec = 0) 24 { 25 RedisHelper.Set(key, t, expiresSec); 26 } 27 28 public async Task SetAsync(string key, object t, int expiresSec = 0) 29 { 30 await RedisHelper.SetAsync(key, t, expiresSec); 31 } 32 }
appsetting.json
"Cache": { "RedisConnection": "127.0.0.1:6888,password=,defaultDatabase=2,poolsize=50,connectTimeout=5000,syncTimeout=10000,prefix=cs_redis_:$$$" }
Startup
1 services.AddScoped<IRedisClient, CustomerRedis>(); 2 3 var redisConn = Configuration["Cache:RedisConnection"]; 4 //services.Configure<WeChatPayOptions>(Configuration.GetSection("WeChatPay")); 5 var csredis = new CSRedis.CSRedisClient(redisConn); 6 RedisHelper.Initialization(csredis);
调用
1 private readonly IRedisClient _redisClient; 2 public ValuesController(IRedisClient redisClient) 3 { 4 this._redisClient = redisClient; 5 } 6 7 [HttpGet("test")] 8 public async Task<ActionResult> Test() 9 { 10 await this._redisClient.SetAsync("test", "test",100); 11 var res = await this._redisClient.GetAsync("test"); 12 return Ok(res); 13 }
更多使用请移至 https://github.com/2881099/csredis