栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

Redis在.NET 5+项目的应用(CSRedisCore)

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Redis在.NET 5+项目的应用(CSRedisCore)

引用包
dotnet add package CSRedisCore --version 3.6.8
应用模式
  • 工厂模式
  • 集成到构造器类
工厂模式
  1. 添加工具类:CSRedisHelper.cs
	/// 
    /// Redis帮助类
    /// 
    public class CSRedisHelper
    {
        static CSRedisClient redisManger = null;
        static CSRedisClient GetClient()
        {
            return redisManger;
        }
        public CSRedisHelper(string connectionString)
        {
            redisManger = new CSRedisClient(connectionString);      //Redis的连接字符串
        }
        /// 
        /// 获取指定的键的集合
        /// 
        /// 
        /// 
        public List Keys(string pattern = null)
        {
            if (string.IsNullOrWhiteSpace(pattern))
                pattern = "*";
            return GetClient().Keys(pattern).ToList();
        }
    }
  1. 添加工厂类:RedisClientFactory.cs
	/// 
    /// Redis工厂类
    /// 
    public class RedisClientFactory
    {
        private static readonly ConcurrentDictionary CSRedisClients =
            new ConcurrentDictionary();
            
        public static CSRedisHelper GetClient(string connectionString)
        {
            return CSRedisClients.GetOrAdd(connectionString, new CSRedisHelper(connectionString));
        }
    }
  1. 测试调用
		protected static readonly CSRedisHelper RedisService = 
				RedisClientFactory.GetClient("连接字符串");
        public static void TestDeleteAll()
        {
            var watch = new Stopwatch();
            watch.Start();
            var keys = RedisService.Keys();
            if (!keys.IsNullOrNotData())
            {
                RedisService.KeyDel(keys);
            }
            watch.Stop();
            var ts = watch.Elapsed;

            Console.WriteLine($"删除{keys.Count}花费了{ts.TotalSeconds}");
        }
集成到构造器类
  1. 添加拓展工具类CacheExtension.cs
	public static class CacheExtension
    {
        /// 
        /// 使用缓存
        /// 
        /// 建造者
        /// 
        public static IHostBuilder UseCache(this IHostBuilder hostBuilder)
        {
            hostBuilder.ConfigureServices((buidlerContext, services) =>
            {
                var CacheType = buidlerContext.Configuration["CacheType"].ToString();
                switch (CacheType)
                {
                    case "Memory": services.AddDistributedMemoryCache(); break;
                    case "Redis":
                        {
                            // => 初始化redis的两种使用方式
                            var csredis = new CSRedisClient(buidlerContext.Configuration["RedisConn"].ToString());
                            // 使用RedisHelper
                            services.AddSingleton(csredis);
                            RedisHelper.Initialization(csredis);

                            // 依赖注入使用自定义工具类
                            services.AddSingleton(new CSRedisCache(csredis));
                        }; break;
                    default: throw new Exception("缓存类型无效");
                }
            });
            return hostBuilder;
        }
    }
  1. 添加接口:ICSRedisCache
	/// 
    /// CSRedis帮助类
    /// 
    public interface ICSRedisCache
    {
        /// 
        /// 根据Key获取值
        /// 
        /// 
        /// 
        /// 
        T StringGet(string key);
    }
  1. 添加实现类:CSRedisCache
    /// 
    /// Redis帮助实现类
    /// 
    public class CSRedisCache : ICSRedisCache
    {
        private CSRedisClient csredis;

        public CSRedisCache(CSRedisClient csredis)
        {
            this.csredis = csredis;
        }
        /// 
        /// 获取指定key的值
        /// 
        /// 
        /// 
        /// 
        public T StringGet(string key)
        {
            return csredis.Get(key);
        }
    }
  1. 在Program.cs中调用
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup();
                })
            // => 使用Redis
            .UseCache();
  1. 接口测试
        private readonly ICSRedisCache _iCSRedisCache;
        /// 
        /// 构造函数依赖注入
        /// 
        /// 
        public TestRedisController(ICSRedisCache cSRedisCache)
        {
            _iCSRedisCache = cSRedisCache;
        }
        [HttpGet]
        public ActionResult GetValueByKey(string key)
        {
            var value = _iCSRedisCache.StringGet(key);
            return Ok(value);
        }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/911453.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号