首先 Nuget CSRedisCore
新建一个 IRedisClient
接口
public interface IRedisClient
{
string Get(string key);
Task<string> GetAsync(string key);
void Set(string key, object t, int expiresSec = 0);
Task SetAsync(string key, object t, int expiresSec = 0);
T Get<T>(string key) where T : new();
Task<T> GetAsync<T>(string key) where T : new();
}
实现接口
public class CustomerRedis : IRedisClient
{
public string Get(string key)
{
return RedisHelper.Get(key);
}
public T Get<T>(string key) where T : new()
{
return RedisHelper.Get<T>(key);
}
public async Task<string> GetAsync(string key)
{
return await RedisHelper.GetAsync(key);
}
public async Task<T> GetAsync<T>(string key) where T : new()
{
return await RedisHelper.GetAsync<T>(key);
}
public void Set(string key, object t, int expiresSec = 0)
{
RedisHelper.Set(key, t, expiresSec);
}
public async Task SetAsync(string key, object t, int expiresSec = 0)
{
await RedisHelper.SetAsync(key, t, expiresSec);
}
}
appsetting.json
"Cache": {
"RedisConnection": "127.0.0.1:6888,password=,defaultDatabase=2,poolsize=50,connectTimeout=5000,syncTimeout=10000,prefix=cs_redis_:$$$"
}
Startup
services.AddScoped<IRedisClient, CustomerRedis>();
var redisConn = Configuration["Cache:RedisConnection"];
//services.Configure<WeChatPayOptions>(Configuration.GetSection("WeChatPay"));
var csredis = new CSRedis.CSRedisClient(redisConn);
RedisHelper.Initialization(csredis);
调用
private readonly IRedisClient _redisClient;
public ValuesController(IRedisClient redisClient)
{
this._redisClient = redisClient;
}
[HttpGet("test")]
public async Task<ActionResult> Test()
{
await this._redisClient.SetAsync("test", "test",100);
var res = await this._redisClient.GetAsync("test");
return Ok(res);
}