標籤:blog http io ar os sp for strong on
三、程式配置在C# Redis實戰(二)中我們安裝好了Redis的系統服務,此時Redis服務已經運行。現在我們需要讓我們的程式能正確讀取到Redis服務地址等一系列的配置資訊,首先,需要在Web.config檔案中添加如下資訊:
[html] view plaincopy
- <?xml version="1.0" encoding="utf-8"?>
- <!--
- 有關如何配置 ASP.NET 應用程式的詳細資料,請訪問
- http://go.microsoft.com/fwlink/?LinkId=169433
- -->
- <configuration>
- <configSections>
- <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
- <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
- <section name="RedisConfig" type="RedisDemo.RedisConfigInfo, RedisDemo"/>
- </configSections>
- <RedisConfig WriteServerList="127.0.0.1:6379" ReadServerList="127.0.0.1:6379" MaxWritePoolSize="60"
- MaxReadPoolSize="60" AutoStart="true" LocalCacheTime="180" RecordeLog="false">
- </RedisConfig>
- <connectionStrings>
- <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-RedisDemo-20131125110945;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-RedisDemo-20131125110945.mdf" />
- </connectionStrings>
-
- </configuration>
有了以上資訊還不夠,還需要用C#代碼來讀取並且操作,擷取Redis配置的程式如下:
[csharp] view plaincopy
- 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管理類代碼:
[csharp] view plaincopy
- /// <summary>
- /// redis設定檔資訊
- /// </summary>
- private static RedisConfigInfo redisConfigInfo = RedisConfigInfo.GetConfig();
-
- private static PooledRedisClientManager prcm;
-
- /// <summary>
- /// 靜態構造方法,初始化連結池管理對象
- /// </summary>
- static RedisManager()
- {
- CreateManager();
- }
-
-
- /// <summary>
- /// 建立連結池管理對象
- /// </summary>
- 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());
- }
-
- /// <summary>
- /// 用戶端快取作業對象
- /// </summary>
- public static IRedisClient GetClient()
- {
- if (prcm == null)
- CreateManager();
-
- return prcm.GetClient();
- }
如需轉載,請註明出處,本系列博文樣本程式
C# Redis實戰(三)