由于redis是單點,但是項目中不可避免的會使用多臺Redis緩存服務器,那么怎么把緩存的Key均勻的映射到多臺Redis服務器上,且隨著緩存服務器的增加或減少時做到最小化的減少緩存Key的命中率呢?這樣就需要我們自己實現分布式。
Memcached對大家應該不陌生,通過把Key映射到Memcached Server上,實現快速讀取。我們可以動態對其節點增加,并未影響之前已經映射到內存的Key與memcached Server之間的關系,這就是因為使用了一致性哈希。
因為Memcached的哈希策略是在其客戶端實現的,因此不同的客戶端實現也有區別,以Spymemcache、Xmemcache為例,都是使用了KETAMA作為其實現。
因此,我們也可以使用一致性hash算法來解決Redis分布式這個問題。在介紹一致性hash算法之前,先介紹一下我之前想的一個方法,怎么把Key均勻的映射到多臺Redis Server上。
由于LZ水平有限且對Redis研究的不深,文中有寫的不對的地方請指正。
方案一
該方案是前幾天想的一個方法,主要思路是通過對緩存Key中的字母和數字的ascii碼值求sum,該sum值對Redis Server總數取余得到的數字即為該Key映射到的Redis Server,該方法有一個很大的缺陷就是當Redis Server增加或減少時,基本上所有的Key都映射不到對應的的Redis Server了。代碼如下:

/// <summary> /// 根據緩存的Key映射對應的Server /// </summary> /// <param name="Key"></param> /// <returns></returns> public static RedisClient GetRedisClientByKey(string Key) { List<RedisClientInfo> RedisClientList = new List<RedisClientInfo>(); RedisClientList.Add(new RedisClientInfo() { Num = 0, IPPort = "127.0.0.1:6379" }); RedisClientList.Add(new RedisClientInfo() { Num = 1, IPPort = "127.0.0.1:9001" }); char[] charKey = Key.ToCharArray(); //記錄Key中的所有字母與數字的ascii碼和 int KeyNum = 0; //記錄余數 int Num = 0; foreach (var c in charKey) { if ((c >= 'a' && 'z' >= c) || (c >= 'A' && 'Z' >= c)) { System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding(); KeyNum = KeyNum + (int)asciiEncoding.GetBytes(c.ToString())[0]; } if (c >= '1' && '9' >= c) { KeyNum += Convert.ToInt32(c.ToString()); } } Num = KeyNum % RedisClientList.Count; return new RedisClient(RedisClientList.Where(it => it.Num == Num).First().IPPort); } //Redis客戶端信息 public class RedisClientInfo { //Redis Server編號 public int Num { get; set; } //Redis Server IP地址和端口號 public string IPPort { get; set; } }

方案二
1、分布式實現
通過key做一致性哈希,實現key對應redis結點的分布。
一致性哈希的實現:
- hash值計算:通過支持MD5與MurmurHash兩種計算方式,默認是采用MurmurHash,高效的hash計算。
- 一致性的實現:通過java的TreeMap來模擬環狀結構,實現均勻分布
什么也不多說了,直接上代碼吧,LZ也是只知道點皮毛,代碼中還有一些看不懂的地方,留著以后慢慢琢磨

public class KetamaNodeLocator { //原文中的JAVA類TreeMap實現了Comparator方法,這里我圖省事,直接用了net下的SortedList,其中Comparer接口方法) private SortedList<long, string> ketamaNodes = new SortedList<long, string>(); private HashAlgorithm hashAlg; private int numReps = 160; //此處參數與JAVA版中有區別,因為使用的靜態方法,所以不再傳遞HashAlgorithm alg參數 public KetamaNodeLocator(List<string> nodes/*,int nodeCopies*/) { ketamaNodes = new SortedList<long, string>(); //numReps = nodeCopies; //對所有節點,生成nCopies個虛擬結點 foreach (string node in nodes) { //每四個虛擬結點為一組 for (int i = 0; i < numReps / 4; i++) { //getKeyForNode方法為這組虛擬結點得到惟一名稱 byte[] digest = HashAlgorithm.computeMd5(node + i); /** Md5是一個16字節長度的數組,將16字節的數組每四個字節一組,分別對應一個虛擬結點,這就是為什么上面把虛擬結點四個劃分一組的原因*/ for (int h = 0; h < 4; h++) { long m = HashAlgorithm.hash(digest, h); ketamaNodes[m] = node; } } } } public string GetPrimary(string k) { byte[] digest = HashAlgorithm.computeMd5(k); string rv = GetNodeForKey(HashAlgorithm.hash(digest, 0)); return rv; } string GetNodeForKey(long hash) { string rv; long key = hash; //如果找到這個節點,直接取節點,返回 if (!ketamaNodes.ContainsKey(key)) { //得到大于當前key的那個子Map,然后從中取出第一個key,就是大于且離它最近的那個key 說明詳見: http://www.javaeye.com/topic/684087 var tailMap = from coll in ketamaNodes where coll.Key > hash select new { coll.Key }; if (tailMap == null || tailMap.Count() == 0) key = ketamaNodes.FirstOrDefault().Key; else key = tailMap.FirstOrDefault().Key; } rv = ketamaNodes[key]; return rv; } } public class HashAlgorithm { public static long hash(byte[] digest, int nTime) { long rv = ((long)(digest[3 + nTime * 4] & 0xFF) << 24) | ((long)(digest[2 + nTime * 4] & 0xFF) << 16) | ((long)(digest[1 + nTime * 4] & 0xFF) << 8) | ((long)digest[0 + nTime * 4] & 0xFF); return rv & 0xffffffffL; /* Truncate to 32-bits */ } /** * Get the md5 of the given key. */ public static byte[] computeMd5(string k) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] keyBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(k)); md5.Clear(); //md5.update(keyBytes); //return md5.digest(); return keyBytes; } }

2、分布式測試
1、假設有兩個server:0001和0002,循環調用10次看看Key值能不能均勻的映射到server上,代碼如下:
static void Main(string[] args) { //假設的server List<string> nodes = new List<string>() { "0001","0002" }; KetamaNodeLocator k = new KetamaNodeLocator(nodes); string str = ""; for (int i = 0; i < 10; i++) { string Key="user_" + i; str += string.Format("Key:{0}分配到的Server為:{1}\n\n", Key, k.GetPrimary(Key)); } Console.WriteLine(str); Console.ReadLine(); }
程序運行兩次的結果如下,發現Key基本上均勻的分配到Server節點上了。

2、我們在添加一個0003的server節點,代碼如下:
static void Main(string[] args) { //假設的server List<string> nodes = new List<string>() { "0001","0002" ,"0003"}; KetamaNodeLocator k = new KetamaNodeLocator(nodes); string str = ""; for (int i = 0; i < 10; i++) { string Key="user_" + i; str += string.Format("Key:{0}分配到的Server為:{1}\n\n", Key, k.GetPrimary(Key)); } Console.WriteLine(str); Console.ReadLine(); }
程序運行兩次的結果如下:

對比第一次的運行結果發現只有user_5,user_7,user_9的緩存丟失,其他的緩存還可以命中。
3、我們去掉server 0002,運行兩次的結果如下:

對比第二次和本次運行結果發現 user_0,user_1,user_6 緩存丟失。
結論
通過一致性hash算法可以很好的解決Redis分布式的問題,且當Redis server增加或減少的時候,之前存儲的緩存命中率還是比較高的。
http://www.cnblogs.com/lc-chenlong/p/4194150.html
http://www.cnblogs.com/lc-chenlong/p/4195033.html
http://www.cnblogs.com/lc-chenlong/p/3218157.html
本文參考
1、http://blog.csdn.net/chen77716/article/details/5949166
2、http://www.cr173.com/html/6474_2.html
轉:http://www.cnblogs.com/lc-chenlong/p/4195814.html?utm_source=tuicool&utm_medium=referral
posted on 2015-10-20 15:51
fly 閱讀(315)
評論(0) 編輯 收藏 所屬分類:
J2EE-負載均衡