CSRedis是國外大牛寫的。git地址:https://github.com/2881099/csredis,讓咱們看看若是最簡單的 使用一下CSRedis吧。git
獲取Nuget包(目前版本3.0.18)!哈,沒錯,使用前要經過Nuget來安裝下引用,什麼?你不知道怎麼使用Nuget包?對不起,右上角點下「X」 關掉網頁就能夠了。github
nuget Install-Package CSRedisCore
CSRedisCore的使用很簡單,就須要實例化一個CSRedisClient(集羣鏈接池)對象而後初始化一下RedisHelper就能夠了,他的方法名與redis-cli基本保持一致。因此說你能夠像使用redis-cli命令同樣來使用它。redis
1.新建一個 IRedisClient 接口緩存
public interface IRedisClient { string Get(string key); void Set(string key, object t, int expiresSec = 0); T Get<T>(string key) where T : new(); Task<string> GetAsync(string key); Task SetAsync(string key, object t, int expiresSec = 0); Task<T> GetAsync<T>(string key) where T : new(); }
2.實現接口dom
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 void Set(string key, object t, int expiresSec = 0) { RedisHelper.Set(key, t, expiresSec); } 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 async Task SetAsync(string key, object t, int expiresSec = 0) { await RedisHelper.SetAsync(key, t, expiresSec); } }
3.在項目Startup類中 ConfigureServices方法 裏注入並 初始化Redisasync
services.AddScoped<IRedisClient,CustomerRedis>();
var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379"); RedisHelper.Initialization(csredis);//初始化
4.頁面使用,本例以發短信爲例spa
private readonly IRedisClient _redisclient; public SmsServices(IRedisClient redisClient) { _redisclient = redisClient; } public async Task<bool> SendVerifyCode(string phoneNumber) { //create random verify code await _redisclient.SetAsync(userdataKey, randomCode, 300) //send short message } public async Task<bool> VerifyCode(string userCode, string verifycode) { var resultCode = await _redisclient.GetAsync(userdataKey); return verifycode == resultCode; }
5.打開本地的Redis Desktop 可查看到 緩存已經被添加進去了3d