.Net Core使用Redis(CSRedis)

前言

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 可查看到 缓存已经被添加进去了

猜你喜欢

转载自www.cnblogs.com/zhangxiaoyong/p/10732820.html