.net core使用CSRedisCore连接哨兵集群,并用作redis使用分布式缓存。

CSRedisCore是国内大佬出品的一个Redis-Cli-SDK。

Github地址:https://github.com/2881099/csredis

使用此插件作为分布式缓存也十分简单。

一、asp.net core 3.0中使用分布式缓存。

  注意:IDistributedCache是asp.net core中提供的缓存接口。提供了一些基本的方法。

  使用Caching.CSRedis可以方便的实现IDistributedCache接口。

  

          // 通过Caching.CSRedis实现IDistributedCache
      services.AddSingleton<IDistributedCache>(new CSRedisCache(new CSRedisClient("127.0.0.1:6379")));

   此时就可以在构造函数中注入IDistributedCache接口使用了。

  

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IDistributedCache distributedCache)
        {
            _logger = logger;
            _distributedCache = distributedCache;
        }
        [HttpGet]
        public IEnumerable<WeatherForecast> GetDistributeCacheData(string key)
        {
            var cache = _distributedCache.Get(key);
            if (cache == null)
            {
                // 这里应该上锁,否则同时会有多个请求,单机测试无所谓。
                // 模拟获取数据
                Thread.Sleep(1000);
                var result = GetDataByDatabase(key);

                //放到缓存。
                _distributedCache.Set(key, JsonSerializer.SerializeToUtf8Bytes(result));

                return result;
            }
            else
            {
                return JsonSerializer.Deserialize<WeatherForecast[]>(cache);
            }
        }

使用起来十分简单。

二、使用Session。

    asp.net core 3.0中,使用Session是需要IDistributedCache支持的,即使在单机中使用,也要使用基于内存的分布式缓存。

    

  
   // 如果不实现IDistributedCache将会异常。
   services.AddSession();

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      app.UseSession();

    }

  虽然我在上面注入了IDistributedCache接口的实现,已经可以使用Session了,但是我不能区分数据Redis和SessionRedis容器,Session和其他所有的缓存都将放在一个Redist容器中。

  要解决这个问题,则需要注入新的接口。

  还是基于CSRedisCore修改。

  以下基于Caching.CSRedis的源码修改。

  

 // 继承分布式缓存接口。
public interface IDistributedSessionCache : IDistributedCache

使用自定义类继承默认实现。

    /// <summary>
    /// 自定义RedisSession缓存。
    /// </summary>
    public class DistributedRedisSessionStore : DistributedSessionStore
    {
        /// <summary>
        /// 构造函数。
        /// </summary>
        /// <param name="cache">自定义RedisSession缓存,此处使用继承默认接口的自定义接口。</param>
        /// <param name="loggerFactory">日志工厂。</param>
        public DistributedRedisSessionStore(IDistributedSessionCache cache, ILoggerFactory loggerFactory) : base(cache, loggerFactory)
        {
        }
    }

 扩展依赖注入方法

        public static IServiceCollection AddRedisSession(this IServiceCollection services)
        {
            services.TryAddTransient<ISessionStore, DistributedRedisSessionStore>();
            services.AddDataProtection();
            return services;
        }

依赖注入方法

            // 连接Redis的容器,此时6380端口。
       services.AddSingleton<IDistributedSessionCache>(new CSRedisSessionCache(new CSRedisClient("127.0.0.1:6380"))); services.AddRedisSession();

一个简单的测试方法

        public IActionResult GetSessionData(string key)
        {
            if (!HttpContext.Session.Keys.Contains(key))
                HttpContext.Session.Set(key, JsonSerializer.SerializeToUtf8Bytes(DateTime.Now));

            if (HttpContext.Session.TryGetValue(key, out var value))
                return new JsonResult(JsonSerializer.Deserialize<DateTime>(value));
            else
                return new JsonResult(DateTime.Now.AddYears(10));
        }

此时,我在docker停止了6379(普通数据缓存容器),Session依然没有问题。

 普通数据容器已经挂了

区分Session容器和普通数据缓存的代码。

github:https://github.com/yeqifeng2288/Microsoft.Extensions.Caching.CSRedis.Session

猜你喜欢

转载自www.cnblogs.com/yeqifeng2288/p/11959177.html