.Core使用CSRedis

一、为什么选择CSRedis

ServiceStack.Redis 是商业版,免费版有限制;

StackExchange.Redis 是免费版,但是内核在 .NETCore 运行有问题经常 Timeout,暂无法解决;

CSRedis于2016年开始支持.NETCore一直迭代至今,实现了低门槛、高性能,和分区高级玩法的.NETCore redis-cli SDK;

在v3.0版本更新中,CSRedis中的所有方法名称进行了调整,使其和redis-cli保持一致,如果你熟悉redis-cli的命令的话,CSRedis可以直接上手,这样学习成本就降低很多。

二、使用CSRedis

  安装CSRedis

 

 

 在appsettings.json做Redis配置

{
  "Cache": {
    "CacheType": "Redis", //CacheType
    "RedisEndpoint": "127.0.0.1:6379,password=123", //Redis节点地址,定义详见 https://github.com/2881099/csredis
    //如果Redis没有设置密码
    //"RedisEndpoint": "127.0.0.1:6379" //Redis节点地址,定义详见 https://github.com/2881099/csredis
  },
  "AllowedHosts": "*"
}

自定义IHostBuilder扩展方法,注入CSRedis服务

using CSRedis;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;

namespace CSRedisTest
{
    public static class Extention
    {
        /// <summary>
        /// 使用缓存
        /// </summary>
        /// <param name="hostBuilder">建造者</param>
        /// <returns></returns>
        public static IHostBuilder UseCache(this IHostBuilder hostBuilder)
        {
            hostBuilder.ConfigureServices((buidlerContext, services) =>
            {
                var cacheOption = buidlerContext.Configuration.GetSection("Cache").Get<CacheOption>();
                switch (cacheOption.CacheType)
                {
                    case CacheType.Memory: services.AddDistributedMemoryCache(); break;
                    case CacheType.Redis:
                        {
                            var csredis = new CSRedisClient(cacheOption.RedisEndpoint);
                            RedisHelper.Initialization(csredis);
                            services.AddSingleton(csredis);
                            services.AddSingleton<IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
                        }; break;
                    default: throw new Exception("缓存类型无效");
                }
            });

            return hostBuilder;
        }
    }
}

在Program调用该扩展方法

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace CSRedisTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseCache()//调动方法
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

在Controller中使用CSRedis

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CSRedisTest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            //添加数据 字符串键-值对 
            RedisHelper.Set("hello", "1", 60);//设置过期时间,单位秒
            RedisHelper.Set("world", "2");//默认不过期

            // 根据键获取对应的值
            string helloValue=RedisHelper.Get("hello");

            // 移除元素
            RedisHelper.Del("world");

            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
            })
            .ToArray();
        }
    }
}
View Code

我们利用Redis Desktop Manager管理工具查看下数据

 

 

源码:https://github.com/qiuxianhu/CoreComponentDemo

posted @ 2020-07-02 17:37  搬砖滴  阅读(870)  评论(0编辑  收藏  举报