因爲redis是單點,可是項目中不可避免的會使用多臺Redis緩存服務器,那麼怎麼把緩存的Key均勻的映射到多臺Redis服務器上,且隨着緩存服務器的增長或減小時作到最小化的減小緩存Key的命中率呢?這樣就須要咱們本身實現分佈式。html
Memcached對你們應該不陌生,經過把Key映射到Memcached Server上,實現快速讀取。咱們能夠動態對其節點增長,並未影響以前已經映射到內存的Key與memcached Server之間的關係,這就是由於使用了一致性哈希。
由於Memcached的哈希策略是在其客戶端實現的,所以不一樣的客戶端實現也有區別,以Spymemcache、Xmemcache爲例,都是使用了KETAMA做爲其實現。java
所以,咱們也可使用一致性hash算法來解決Redis分佈式這個問題。在介紹一致性hash算法以前,先介紹一下我以前想的一個方法,怎麼把Key均勻的映射到多臺Redis Server上。node
因爲LZ水平有限且對Redis研究的不深,文中有寫的不對的地方請指正。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; } }
經過key作一致性哈希,實現key對應redis結點的分佈。數組
一致性哈希的實現:緩存
什麼也很少說了,直接上代碼吧,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; } }
一、假設有兩個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節點上了。ide
二、咱們在添加一個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的緩存丟失,其餘的緩存還能夠命中。
三、咱們去掉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