ServiceStack.Redis 是一個C#訪問Redis的客戶端,能夠說能夠經過它實現全部須要Redis-Cli的功能。可是今天我在主Redis 實例設置了訪問密碼,而在slave 上沒有設置,我經過一個緩存工廠來獲取鏈接。在redisClient實例化能夠直接設置密碼。redis
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 passwordui
slave 指定master密碼:config set masterauth password 就能夠實如今master設置密碼,而且不須要重啓redis實例 很是方便,可是這種方式重啓後失效。this