serviceStack.Redis 在PooledRedisClientManager 中設置密碼


ServiceStack.Redis 是一個C#訪問Redis的客戶端,可以說可以通過它實現所有需要Redis-Cli的功能。但是今天我在主Redis 實例設置了訪問密碼,而在slave 上沒有設置,我通過一個緩存工廠來獲取連接。在redisClient實例化可以直接設置密碼。

 1  /// <summary>
 2     /// 緩存客戶端管理器工廠
 3     /// </summary>
 4     public class PoolManagerFactory
 5     {
 6         private static PooledRedisClientManager Manager = null;
 7         public static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts, int initialDB = 0)
 8         {
 9             if (Manager == null)
10             {
11                 Manager = new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig()
12                 {
13                     MaxWritePoolSize = 5,
14                     MaxReadPoolSize = 5,
15                     AutoStart = true
16                 }, initialDB, 50, 5);
17             }
18             return Manager;
19         }
20 
21     }

 

我一直認為readWriteHosts數組中只能輸入ip:port來代表一個redis 實例的連接,但是如何把密碼加在里面呢?想不到如何實現,只能下載了源代碼查看,原來這個實現是通過分隔字符串來實現,

 1     /// <summary>
 2         /// IP地址中可以加入auth驗證   password@ip:port
 3         /// </summary>
 4         /// <param name="hosts"></param>
 5         /// <returns></returns>
 6         public static List<RedisEndpoint> ToRedisEndPoints(this IEnumerable<string> hosts)
 7         {
 8             if (hosts == null) return new List<RedisEndpoint>();
 9             //redis終結點的列表
10             var redisEndpoints = new List<RedisEndpoint>();
11             foreach (var host in hosts)
12             {
13                 RedisEndpoint endpoint;
14                 string[] hostParts;
15                 if (host.Contains("@"))
16                 {
17                     hostParts = host.SplitOnLast('@');
18                     var password = hostParts[0];
19                     hostParts = hostParts[1].Split(':');
20                     endpoint = GetRedisEndPoint(hostParts);
21                     endpoint.Password = password;
22                 }
23                 else
24                 {
25                     hostParts = host.Split(':');
26                     endpoint = GetRedisEndPoint(hostParts);
27                 }
28                 redisEndpoints.Add(endpoint);
29             }
30             return redisEndpoints;
31         }

在ip:port前面加上@用來表示密碼,比如password@ip:port    ,現在才知道能看到源碼的程序是多么的幸福的一件事。開源偉大。

master:設置密碼:config set requirepass password

 

slave 指定master密碼:config set masterauth password   就可以實現在master設置密碼,並且不需要重啟redis實例 非常方便,但是這種方式重啟后失效。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM