memcached(八)一致性哈希高级应用

来源:互联网 发布:淘宝点击量是什么意思 编辑:程序博客网 时间:2024/05/18 02:28

memcached(八)一致性哈希高级应用

    博客分类: 
  • memcached/redis/localcache
 
简介 
    一致性哈希算法在1997年由麻省理工学院提出(参见扩展阅读[1]),设计目标是为了解决因特网中的热点(Hot spot)问题,初衷和CARP十分类似。一致性哈希修正了CARP使用的简单哈希算法带来的问题,使得DHT可以在P2P环境中真正得到应用。 
    英文解释 
    Consistent hashing is a scheme that provides hash table functionality in a way that the addition or removal of one slot does not significantly change the mapping of keys to slots. 

 

哈希算法 
    一致性哈希提出了在动态变化的Cache环境中,哈希算法应该满足的4个适应条件: 

平衡性(Balance) 
平衡性是指哈希的结果能够尽可能分布到所有的缓冲中去,这样可以使得所有的缓冲空间都得到利用。很多哈希算法都能够满足这一条件。 

单调性(Monotonicity) 
单调性是指如果已经有一些内容通过哈希分派到了相应的缓冲中,又有新的缓冲区加入到系统中,那么哈希的结果应能够保证原有已分配的内容可以被映射到新的缓冲区中去,而不会被映射到旧的缓冲集合中的其他缓冲区。(这段翻译信息有负面价值的,当缓冲区大小变化时Consistent hashing尽量保护已分配的内容不会被重新映射到新缓冲区。) 
简单的哈希算法往往不能满足单调性的要求,如最简单的线性哈希: 
x → ax + b mod (P) 
在上式中,P表示全部缓冲的大小。不难看出,当缓冲大小发生变化时(从P1到P2),原来所有的哈希结果均会发生变化,从而不满足单调性的要求。 
哈希结果的变化意味着当缓冲空间发生变化时,所有的映射关系需要在系统内全部更新。而在P2P系统内,缓冲的变化等价于Peer加入或退出系统,这一情况在P2P系统中会频繁发生,因此会带来极大计算和传输负荷。单调性就是要求哈希算法能够应对这种情况。 

分散性(Spread) 
在分布式环境中,终端有可能看不到所有的缓冲,而是只能看到其中的一部分。当终端希望通过哈希过程将内容映射到缓冲上时,由于不同终端所见的缓冲范围有可能不同,从而导致哈希的结果不一致,最终的结果是相同的内容被不同的终端映射到不同的缓冲区中。这种情况显然是应该避免的,因为它导致相同内容被存储到不同缓冲中去,降低了系统存储的效率。分散性的定义就是上述情况发生的严重程度。好的哈希算法应能够尽量避免不一致的情况发生,也就是尽量降低分散性。 

负载(Load) 
负载问题实际上是从另一个角度看待分散性问题。既然不同的终端可能将相同的内容映射到不同的缓冲区中,那么对于一个特定的缓冲区而言,也可能被不同的用户映射为不同的内容。与分散性一样,这种情况也是应当避免的,因此好的哈希算法应能够尽量降低缓冲的负荷。 

结论 
    一致性哈希基本解决了在P2P环境中最为关键的问题——如何在动态的网络拓扑中分布存储和路由。每个节点仅需维护少量相邻节点的信息,并且在节点加入/退出系统时,仅有相关的少量节点参与到拓扑的维护中。所有这一切使得一致性哈希成为第一个实用的DHT算法。 
    但是一致性哈希的路由算法尚有不足之处。在查询过程中,查询消息要经过O(N)步(O(N)表示与N成正比关系,N代表系统内的节点总数)才能到达被查询的节点。不难想象,当系统规模非常大时,节点数量可能超过百万,这样的查询效率显然难以满足使用的需要。换个角度来看,即使用户能够忍受漫长的时延,查询过程中产生的大量消息也会给网络带来不必要的负荷。 

memcache的客户端分布式 
memcached的客户端分布式采用了一致性哈希算法,流程如下: 




xmemcached的Ketama源码解析 
初始化 
Java代码  收藏代码
  1. MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddressMap("......"));  
  2. builder.setSessionLocator(new KetamaMemcachedSessionLocator());  


net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator的细节 
Java代码  收藏代码
  1. /** 
  2.  *Copyright [2009-2010] [dennis zhuang(killme2008@gmail.com)] 
  3.  *Licensed under the Apache License, Version 2.0 (the "License"); 
  4.  *you may not use this file except in compliance with the License. 
  5.  *You may obtain a copy of the License at 
  6.  *             http://www.apache.org/licenses/LICENSE-2.0 
  7.  *Unless required by applicable law or agreed to in writing, 
  8.  *software distributed under the License is distributed on an "AS IS" BASIS, 
  9.  *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
  10.  *either express or implied. See the License for the specific language governing permissions and limitations under the License 
  11.  */  
  12. package net.rubyeye.xmemcached.impl;  
  13.   
  14. import java.net.InetSocketAddress;  
  15. import java.util.ArrayList;  
  16. import java.util.Collection;  
  17. import java.util.List;  
  18. import java.util.Random;  
  19. import java.util.SortedMap;  
  20. import java.util.TreeMap;  
  21.   
  22. import net.rubyeye.xmemcached.HashAlgorithm;  
  23. import net.rubyeye.xmemcached.networking.MemcachedSession;  
  24.   
  25. import com.google.code.yanf4j.core.Session;  
  26.   
  27. /** 
  28.  * ConnectionFactory instance that sets up a ketama compatible connection. 
  29.  * 
  30.  * <p> 
  31.  * This implementation piggy-backs on the functionality of the 
  32.  * <code>DefaultConnectionFactory</code> in terms of connections and queue 
  33.  * handling. Where it differs is that it uses both the <code> 
  34.  * KetamaNodeLocator</code> 
  35.  * and the <code>HashAlgorithm.KETAMA_HASH</code> to provide consistent node 
  36.  * hashing. 
  37.  * 
  38.  * @see http://www.last.fm/user/RJ/journal/2007/04/10/392555/ 
  39.  * 
  40.  * </p> 
  41.  */  
  42. /** 
  43.  * Consistent Hash Algorithm implementation,based on TreeMap.tailMap(hash) 
  44.  * method. 
  45.  *  
  46.  * @author dennis 
  47.  *  
  48.  */  
  49. public class KetamaMemcachedSessionLocator extends  
  50. AbstractMemcachedSessionLocator {  
  51.   
  52.     static final int NUM_REPS = 160;  
  53.     private transient volatile TreeMap<Long, List<Session>> ketamaSessions = new TreeMap<Long, List<Session>>();  
  54.     private final HashAlgorithm hashAlg;  
  55.     private volatile int maxTries;  
  56.     private final Random random = new Random();  
  57.   
  58.     /** 
  59.      * compatible with nginx-upstream-consistent,patched by wolfg1969 
  60.      */  
  61.     static final int DEFAULT_PORT = 11211;  
  62.     private final boolean cwNginxUpstreamConsistent;  
  63.   
  64.     public KetamaMemcachedSessionLocator() {  
  65.         this.hashAlg = HashAlgorithm.KETAMA_HASH;  
  66.         this.cwNginxUpstreamConsistent = false;  
  67.     }  
  68.   
  69.     public KetamaMemcachedSessionLocator(boolean cwNginxUpstreamConsistent) {  
  70.         this.hashAlg = HashAlgorithm.KETAMA_HASH;  
  71.         this.cwNginxUpstreamConsistent = cwNginxUpstreamConsistent;  
  72.     }  
  73.   
  74.     public KetamaMemcachedSessionLocator(HashAlgorithm alg) {  
  75.         this.hashAlg = alg;  
  76.         this.cwNginxUpstreamConsistent = false;  
  77.     }  
  78.   
  79.     public KetamaMemcachedSessionLocator(HashAlgorithm alg,  
  80.             boolean cwNginxUpstreamConsistent) {  
  81.         this.hashAlg = alg;  
  82.         this.cwNginxUpstreamConsistent = cwNginxUpstreamConsistent;  
  83.     }  
  84.   
  85.     public KetamaMemcachedSessionLocator(List<Session> list, HashAlgorithm alg) {  
  86.         super();  
  87.         this.hashAlg = alg;  
  88.         this.cwNginxUpstreamConsistent = false;  
  89.         this.buildMap(list, alg);  
  90.     }  
  91.   
  92.     /** 
  93.     构建hash table的方法 
  94.     list 基于IP的memcached列表 
  95.     alg 使用的算法 
  96.     */  
  97.     private final void buildMap(Collection<Session> list, HashAlgorithm alg) {  
  98.         TreeMap<Long, List<Session>> sessionMap = new TreeMap<Long, List<Session>>();  
  99.   
  100.         for (Session session : list) {  
  101.             //变量中,保存的是IP和端口拼接的字符串,/10.10.160.153:11211  
  102.             String sockStr = null;  
  103.             if (this.cwNginxUpstreamConsistent) {  
  104.                 InetSocketAddress serverAddress = session  
  105.                         .getRemoteSocketAddress();  
  106.                 sockStr = serverAddress.getAddress().getHostAddress();  
  107.                 if (serverAddress.getPort() != DEFAULT_PORT) {  
  108.                     sockStr = sockStr + ":" + serverAddress.getPort();  
  109.                 }  
  110.             } else {  
  111.                 if (session instanceof MemcachedTCPSession) {  
  112.                     // Always use the first time resolved address.  
  113.                     sockStr = ((MemcachedTCPSession) session)  
  114.                             .getInetSocketAddressWrapper()  
  115.                             .getRemoteAddressStr();  
  116.                 }  
  117.                 if (sockStr == null) {  
  118.                     sockStr = String.valueOf(session.getRemoteSocketAddress());  
  119.                 }  
  120.             }  
  121.             /** 
  122.              * Duplicate 160 X weight references 
  123.              */  
  124.             int numReps = NUM_REPS;  
  125.             if (session instanceof MemcachedTCPSession) {  
  126.                 numReps *= ((MemcachedSession) session).getWeight();  
  127.             }  
  128.             if (alg == HashAlgorithm.KETAMA_HASH) {  
  129.                 //此处表示将1个节点,复制成160个虚拟节点  
  130.                 //numReps / 4,是因为每次md5运算,有128位,即:16字节  
  131.                 //虽然最后转换成了long类型,但是他的取值范围不是long的最大值(8字节),而是int的最大值(4字节)-2^32至2^32  
  132.                 for (int i = 0; i < numReps / 4; i++) {  
  133.                     byte[] digest = HashAlgorithm.computeMd5(sockStr + "-" + i);  
  134.                     for (int h = 0; h < 4; h++) {  
  135.                         long k = (long) (digest[3 + h * 4] & 0xFF) << 24  
  136.                                 | (long) (digest[2 + h * 4] & 0xFF) << 16  
  137.                                 | (long) (digest[1 + h * 4] & 0xFF) << 8  
  138.                                 | digest[h * 4] & 0xFF;  
  139.                         this.getSessionList(sessionMap, k).add(session);  
  140.                     }  
  141.   
  142.                 }  
  143.             } else {  
  144.                 for (int i = 0; i < numReps; i++) {  
  145.                     long key = alg.hash(sockStr + "-" + i);  
  146.                     this.getSessionList(sessionMap, key).add(session);  
  147.                 }  
  148.             }  
  149.         }  
  150.         this.ketamaSessions = sessionMap;  
  151.         this.maxTries = list.size();  
  152.     }  
  153.   
  154.     private List<Session> getSessionList(  
  155.             TreeMap<Long, List<Session>> sessionMap, long k) {  
  156.         List<Session> sessionList = sessionMap.get(k);  
  157.         if (sessionList == null) {  
  158.             sessionList = new ArrayList<Session>();  
  159.             sessionMap.put(k, sessionList);  
  160.         }  
  161.         return sessionList;  
  162.     }  
  163.   
  164.     /** 
  165.     根据缓存的key,查找存储节点 
  166.     */  
  167.     public final Session getSessionByKey(final String key) {  
  168.         if (this.ketamaSessions == null || this.ketamaSessions.size() == 0) {  
  169.             return null;  
  170.         }  
  171.         long hash = this.hashAlg.hash(key);  
  172.         Session rv = this.getSessionByHash(hash);  
  173.         int tries = 0;  
  174.         //检查Session是否可用,如果不可用,则跳过此节点,返回下一个临近节点  
  175.         while (!this.failureMode && (rv == null || rv.isClosed())  
  176.                 && tries++ < this.maxTries) {  
  177.             hash = this.nextHash(hash, key, tries);  
  178.             rv = this.getSessionByHash(hash);  
  179.         }  
  180.         return rv;  
  181.     }  
  182.   
  183.     /** 
  184.     根据缓存的key计算出的hash值,取出对应的Session 
  185.     */  
  186.     public final Session getSessionByHash(final long hash) {  
  187.         TreeMap<Long, List<Session>> sessionMap = this.ketamaSessions;  
  188.         if (sessionMap.size() == 0) {  
  189.             return null;  
  190.         }  
  191.         Long resultHash = hash;  
  192.         if (!sessionMap.containsKey(hash)) {  
  193.             // Java 1.6 adds a ceilingKey method, but xmemcached is compatible  
  194.             // with jdk5,So use tailMap method to do this.  
  195.             //取出TreeMap中,索引大于等于hash的map值,结果是排序的  
  196.             SortedMap<Long, List<Session>> tailMap = sessionMap.tailMap(hash);  
  197.             if (tailMap.isEmpty()) {  
  198.                 resultHash = sessionMap.firstKey();  
  199.             } else {  
  200.                 resultHash = tailMap.firstKey();  
  201.             }  
  202.         }  
  203.         //  
  204.         // if (!sessionMap.containsKey(resultHash)) {  
  205.         // resultHash = sessionMap.ceilingKey(resultHash);  
  206.         // if (resultHash == null && sessionMap.size() > 0) {  
  207.         // resultHash = sessionMap.firstKey();  
  208.         // }  
  209.         // }  
  210.         List<Session> sessionList = sessionMap.get(resultHash);  
  211.         if (sessionList == null || sessionList.size() == 0) {  
  212.             return null;  
  213.         }  
  214.         int size = sessionList.size();  
  215.         return sessionList.get(this.random.nextInt(size));  
  216.     }  
  217.   
  218.     public final long nextHash(long hashVal, String key, int tries) {  
  219.         long tmpKey = this.hashAlg.hash(tries + key);  
  220.         hashVal += (int) (tmpKey ^ tmpKey >>> 32);  
  221.         hashVal &= 0xffffffffL; /* truncate to 32-bits */  
  222.         return hashVal;  
  223.     }  
  224.   
  225.     public final void updateSessions(final Collection<Session> list) {  
  226.         this.buildMap(list, this.hashAlg);  
  227.     }  
  228. }  


动态改变被监听服务器 
Xmemcached支持动态的增加或者删除监听服务器,方式如下: 
Java代码  收藏代码
  1. MemcachedClient client=new XMemcachedClient(AddrUtil.getAddresses("server1:11211 server2:11211"));     
  2. //Add two new memcached nodes     
  3. client.addServer("server3:11211 server4:11211");     
  4. //Remove memcached servers     
  5. client.removeServer("server1:11211 server2:11211");  


客户端配置 
结合zookeeper,可以将一致性哈希表放到zookeeper中。当节点发生变化,人工干预比较妨那改变,调用public final void updateSessions(final Collection<Session> list) 接口即可。其中ZooKeeper客户端推荐使用apache-curator,因为: 
  • 封装ZooKeeper client与ZooKeeper server之间的连接处理;
  • 提供了一套Fluent风格的操作API;
  • 提供ZooKeeper各种应用场景(recipe, 比如共享锁服务, 集群领导选举机制)的抽象封装。

其中根据个人经验,ZooKeeper监听配置文件,原生客户端只监听一次,触发事件之后,监听器即被移除。这是个陷阱,而curator很好的解决了诸如此类的问题。
0 0
原创粉丝点击