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

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 = true16 }, initialDB, 50, 5);17 }18 return Manager;19 }20 21 }
我一直認(rèn)為readWriteHosts數(shù)組中只能輸入ip:port來代表一個redis 實例的連接,但是如何把密碼加在里面呢?想不到如何實現(xiàn),只能下載了源代碼查看,原來這個實現(xiàn)是通過分隔字符串來實現(xiàn),

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終結(jié)點的列表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 else24 {25 hostParts = host.Split(':');26 endpoint = GetRedisEndPoint(hostParts);27 }28 redisEndpoints.Add(endpoint);29 }30 return redisEndpoints;31 }
在ip:port前面加上@用來表示密碼,比如password@ip:port ,現(xiàn)在才知道能看到源碼的程序是多么的幸福的一件事。開源偉大。
master:設(shè)置密碼:config set requirepass password
slave 指定master密碼:config set masterauth password 就可以實現(xiàn)在master設(shè)置密碼,并且不需要重啟redis實例 非常方便,但是這種方式重啟后失效。
新聞熱點
疑難解答