C# Redis实战(三)

三、程序配置

在C# Redis实战(二)中我们安装好了Redis的系统服务,此时Redis服务已经运行。
现在我们需要让我们的程序能正确读取到Redis服务地址等一系列的配置信息,首先,需要在Web.config文件中添加如下信息:



  
    
    

了以上信息还不够,还需要用C#代码来读取并且操作,获取Redis配置的程序如下:
 public static RedisConfigInfo GetConfig()
        {
            RedisConfigInfo section = (RedisConfigInfo)ConfigurationManager.GetSection("RedisConfig");
            return section;
        }

        public static RedisConfigInfo GetConfig(string sectionName)
        {
            RedisConfigInfo section = (RedisConfigInfo)ConfigurationManager.GetSection("RedisConfig");
            if (section == null)
                throw new ConfigurationErrorsException("Section " + sectionName + " is not found.");
            return section;
        }

Redis管理类代码:
 /// 
        /// redis配置文件信息
        /// 
        private static RedisConfigInfo redisConfigInfo = RedisConfigInfo.GetConfig();

        private static PooledRedisClientManager prcm;

        /// 
        /// 静态构造方法,初始化链接池管理对象
        /// 
        static RedisManager()
        {
            CreateManager();
        }


        /// 
        /// 创建链接池管理对象
        /// 
        private static void CreateManager()
        {
            string[] writeServerList = SplitString(redisConfigInfo.WriteServerList, ",");
            string[] readServerList = SplitString(redisConfigInfo.ReadServerList, ",");

            prcm = new PooledRedisClientManager(readServerList, writeServerList,
                             new RedisClientManagerConfig
                             {
                                 MaxWritePoolSize = redisConfigInfo.MaxWritePoolSize,
                                 MaxReadPoolSize = redisConfigInfo.MaxReadPoolSize,
                                 AutoStart = redisConfigInfo.AutoStart,
                             });
        }

        private static string[] SplitString(string strSource, string split)
        {
            return strSource.Split(split.ToArray());
        }

        /// 
        /// 客户端缓存操作对象
        /// 
        public static IRedisClient GetClient()
        {
            if (prcm == null)
                CreateManager();

            return prcm.GetClient();
        }


如需转载,请注明出处, 本系列博文示例程序下载地址

转载于:https://www.cnblogs.com/QiuJL/p/4524200.html

你可能感兴趣的:(C# Redis实战(三))