Net Core使用Redis(CSRedis)

14 篇文章 1 订阅

引用地址:.Net Core使用Redis(CSRedis)

CSRedis是国外大牛写的。git地址:GitHub - 2881099/csredis: .NET Core or .NET Framework 4.0+ client for Redis and Redis Sentinel (2.8) and Cluster. Includes both synchronous and asynchronous clients.,让我们看看如果最简单的 使用一下CSRedis吧。

2|0引入NuGet

获取Nuget包(目前版本3.0.18)!哈,没错,使用前要通过Nuget来安装下引用,什么?你不知道怎么使用Nuget包?对不起,右上角点下“X” 关掉网页就可以了。

nuget Install-Package CSRedisCore

3|0 基本使用

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

redis有5大数据类型:string/list/hash/set/zset
下面作为示例,我们操作最简单的string:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //根据连接信息构造客户端对象
            var redis = new CSRedis.CSRedisClient("192.168.3.42:6500,password=123456,defaultDatabase=0,poolsize=500,ssl=false,writeBuffer=10240,prefix=test_");
            //redis中的string存取
            redis.Set("name", "小明");
            var name= redis.Get("name");
            Console.WriteLine($"name={name}");

            redis.Set("birth", DateTime.Now);
            var birth = redis.Get<DateTime>("birth");
            Console.WriteLine($"birth={birth}");

            redis.Set("info", new {sex="female",age="20" });
            var info = redis.Get<object>("info");
            Console.WriteLine($"info={info}");

            Console.WriteLine("ok");
            Console.ReadLine();

        }
    }
}

输出的效果如下:

上面的代码中,我们在存储数据的时候并没有携带参数,其实我们也可以将redis-cli中支持的参数传递进去:

注意:
因为csredis的方法名和redis-cli的命令名称高度一致,所以剩余的基本用法就不用再说了。。。

三、发布订阅
static void Main(string[] args)
 {
     Console.WriteLine($"main-thread:{Thread.CurrentThread.ManagedThreadId}");
     var redis = new CSRedis.CSRedisClient("192.168.3.42:6500,password=123456,defaultDatabase=0,poolsize=500,ssl=false,writeBuffer=10240,prefix=test_");

     //订阅
     var sub = redis.Subscribe(
        ("chan1", msg => Console.WriteLine($"chan1-thread:{Thread.CurrentThread.ManagedThreadId},{msg.Body}")
     ),
        ("chan2", msg => Console.WriteLine($"chan2-thread:{Thread.CurrentThread.ManagedThreadId},{msg.Body}")
     ));
     //发布
     redis.Publish("chan1", "xiaoming");
     redis.Publish("chan2", "xiaohua");

     Console.WriteLine("ok");
     Console.ReadLine();
 }

运行效果:

此时,通过redis客户端发布数据,可看到控制台输出:


四、管道
使用管道模式,打包多条命令一起执行,从而提高性能。

static void Main(string[] args)
{
    var redis = new CSRedis.CSRedisClient("192.168.3.42:6500,password=123456,defaultDatabase=0,poolsize=500,ssl=false,writeBuffer=10240,prefix=test_");

    var ret1 = redis.StartPipe().Set("a", "1").Get("a").EndPipe();
    Console.WriteLine($"{string.Join(",",ret1)}");
    var ret2 = redis.StartPipe(p => p.Set("a", "1").Get("a"));
    Console.WriteLine($"{string.Join(",", ret2)}");

    var ret3 = redis.StartPipe().Get("b").Get("a").Get("a").EndPipe();
    Console.WriteLine($"{string.Join(",", ret3[0]==null,ret3[1],ret3[2])}");

    Console.WriteLine("ok");
    Console.ReadLine();
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值