zoukankan      html  css  js  c++  java
  • .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();

    一个简单的测试方法

            [HttpGet]
            public IActionResult GetSessionData(string key)
            {
                var msg = HttpContext.Connection.LocalPort.ToString();
                DateTime dateTime = default;
                if (HttpContext.Session.TryGetValue(key, out var value))
                    dateTime = JsonSerializer.Deserialize<DateTime>(value);
                else
                {
                    dateTime = DateTime.Now;
                    HttpContext.Session.Set(key, JsonSerializer.SerializeToUtf8Bytes(dateTime));
                }
    
                _logger.LogInformation($"本次连接端口{msg},通过Session获得时间值{dateTime}");
                return new JsonResult(dateTime);
            }

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

     普通数据容器已经挂了

     分别启用端口5002和5003,进行分布式session是否有效。

       可以看到是有效的。

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

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

  • 相关阅读:
    如何:创建自定义 HTTP 模块
    [转]开源邮件系统
    [转]开源.NET邮件服务器
    [转]文件上传及图片水印
    oracle存储过程学习收集|韩顺平oracle视频教程|
    PLSQL自动输入select * from|附件在cnblogs文件|
    oracle有规律数据触发器实现递增(NC地区分类)|更新一路case简化|
    oracle中的几种循环|转|
    官方解释sqlplus /nolog conn /as sysdba无密码可登陆
    建工项目对账查询引擎sql
  • 原文地址:https://www.cnblogs.com/yeqifeng2288/p/11959177.html
Copyright © 2011-2022 走看看