前言
CSRedis是國外大牛寫的。git地址:https://github.com/2881099/csredis,讓我們看看如果最簡單的 使用一下CSRedis吧。
引入NuGet
獲取Nuget包(目前版本3.0.18)!哈,沒錯,使用前要通過Nuget來安裝下引用,什么?你不知道怎么使用Nuget包?對不起,右上角點下“X” 關掉網頁就可以了。
nuget Install-Package CSRedisCore
基本使用
CSRedisCore的使用很簡單,就需要實例化一個CSRedisClient(集群連接池)對象然后初始化一下RedisHelper就可以了,他的方法名與redis-cli基本保持一致。所以說你可以像使用redis-cli命令一樣來使用它。
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.實現接口
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方法 里注入並 初始化Redis
services.AddScoped<IRedisClient,CustomerRedis>();
var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379"); RedisHelper.Initialization(csredis);//初始化
4.頁面使用,本例以發短信為例
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 可查看到 緩存已經被添加進去了