Jedis一致性hash與sharding

 

=

=

=

Jedis一致性hash與sharding https://blog.csdn.net/javahongxi/article/details/79500755

    一、Jedis一致性hash

    利用緩存技術,不僅可以提升系統性能,還能緩解系統故障。對於redis 3.0以下的版本,redis-server沒有sharding的功能,只有master-slave模式。目前企業用的普遍都是隻有m/s模式的redis多實例部署,無論是master還是slave掛掉,都需要調整程序配置(或代碼)。Jedis爲我們提供了編程級別的sharding方式,本文主要介紹相關API使用方法。

     Jedis中sharding基於一致性hash算法,hash值計算採取MD5作爲輔助,此算法似乎已成事實上的標準,不過較新的版本採用的是谷歌的murmur_hash算法(MD5 is really not good?)。

 

[java] view plain copy
 
  1. public interface Hashing {  
  2.   public static final Hashing MURMUR_HASH = new MurmurHash();  
  3.   public ThreadLocal<MessageDigest> md5Holder = new ThreadLocal<MessageDigest>();  
  4.          // 基於MD5的一致性hash算法實現  
  5.   public static final Hashing MD5 = new Hashing() {  
  6.     public long hash(String key) {  
  7.       return hash(SafeEncoder.encode(key));  
  8.     }  
  9.   
  10.     public long hash(byte[] key) {  
  11.       try {  
  12.         if (md5Holder.get() == null) {  
  13.           md5Holder.set(MessageDigest.getInstance("MD5"));  
  14.         }  
  15.       } catch (NoSuchAlgorithmException e) {  
  16.         throw new IllegalStateException("++++ no md5 algorythm found");  
  17.       }  
  18.       MessageDigest md5 = md5Holder.get();  
  19.   
  20.       md5.reset();  
  21.       md5.update(key);  
  22.       byte[] bKey = md5.digest(); // 獲得MD5字節序列  
  23.       // 前四個字節作爲計算參數,最終獲得一個32位int值.    
  24.       // 此種計算方式,能夠確保key的hash值更加“隨即”/“離散”    
  25.       // 如果hash值過於密集,不利於一致性hash的實現(特別是有“虛擬節點”設計時)   
  26.       long res = ((long) (bKey[3] & 0xFF) << 24) | ((long) (bKey[2] & 0xFF) << 16)  
  27.           | ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF);  
  28.       return res;  
  29.     }  
  30.   };  
  31.   
  32.   public long hash(String key);  
  33.   
  34.   public long hash(byte[] key);  
  35. }

    node構建過程:

[java] view plain copy
 
  1. //shards列表爲客戶端提供了所有redis-server配置信息,包括:ip,port,weight,name  
  2. //其中weight爲權重,將直接決定“虛擬節點”的“比例”(密度),權重越高,在存儲是被hash命中的概率越高  
  3. //--其上存儲的數據越多。  
  4. //其中name爲“節點名稱”,jedis使用name作爲“節點hash值”的一個計算參數。  
  5. //---  
  6. //一致性hash算法,要求每個“虛擬節點”必須具備“hash值”,每個實際的server可以有多個“虛擬節點”(API級別)  
  7. //其中虛擬節點的個數= “邏輯區間長度” * weight,每個server的“虛擬節點”將會以“hash”的方式分佈在全局區域中  
  8. //全局區域總長爲2^32.每個“虛擬節點”以hash值的方式映射在全局區域中。  
  9. // 環形:0-->vnode1(:1230)-->vnode2(:2800)-->vnode3(400000)---2^32-->0  
  10. //所有的“虛擬節點”將按照其”節點hash“順序排列(正序/反序均可),因此相鄰兩個“虛擬節點”之間必有hash值差,  
  11. //那麼此差值,即爲前一個(或者後一個,根據實現而定)“虛擬節點”所負載的數據hash值區間。  
  12. //比如hash值爲“2000”的數據將會被vnode1所接受。  
  13. //---  
  14. private void initialize(List<S> shards) {  
  15.     nodes = new TreeMap<Long, S>();//虛擬節點,採取TreeMap存儲:排序,二叉樹  
  16.   
  17.     for (int i = 0; i != shards.size(); ++i) {  
  18.         final S shardInfo = shards.get(i);  
  19.         if (shardInfo.getName() == null)  
  20.                 //當沒有設置“name”是,將“SHARD-NODE”作爲“虛擬節點”hash值計算的參數  
  21.                 //"邏輯區間步長"爲160,爲什麼呢??  
  22.                 //最終多個server的“虛擬節點”將會交錯佈局,不一定非常均勻。  
  23.             for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {  
  24.                 nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo);  
  25.             }  
  26.         else  
  27.             for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {  
  28.                 nodes.put(this.algo.hash(shardInfo.getName() + "*" + shardInfo.getWeight() + n), shardInfo);  
  29.             }  
  30.         resources.put(shardInfo, shardInfo.createResource());  
  31.     }  
  32. }

    node選擇方式:

[java] view plain copy
 
  1. public R getShard(String key) {  
  2.     return resources.get(getShardInfo(key));  
  3. }  
  4. //here:  
  5. public S getShardInfo(byte[] key) {  
  6.         //獲取>=key的“虛擬節點”的列表  
  7.     SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));  
  8.         //如果不存在“虛擬節點”,則將返回首節點。  
  9.     if (tail.size() == 0) {  
  10.         return nodes.get(nodes.firstKey());  
  11.     }  
  12.         //如果存在,則返回符合(>=key)條件的“虛擬節點”的第一個節點  
  13.     return tail.get(tail.firstKey());  
  14. }  

    Jedis sharding默認的一致性hash算法比較適合cache-only的情景,不太適合數據持久化情況。在持久存儲情況下,我們可以使用“強hash”分片,需要重寫hash算法(參加後面的InnerHashing)。強hash算法下,如果某個虛擬節點所在的物理節點故障,將導致數據無法訪問,即無法從虛擬節點列表中刪除失效的server。

    二、API

    ShardedJedis

[java] view plain copy
 
  1. JedisShardInfo sd1 = new JedisShardInfo("127.0.0.1", 6379, 15000);  
  2.         sd1.setPassword("123456");  
  3.         JedisShardInfo sd2 = new JedisShardInfo("127.0.0.1", 6479, 15000);  
  4.         sd2.setPassword("123456");  
  5.         List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();  
  6.         shards.add(sd1);  
  7.         shards.add(sd2);  
  8.         ShardedJedis shardedJedis = new ShardedJedis(shards, new InnerHashing());  
  9.         String key = "k2sdjowejjroer3";  
  10.         shardedJedis.set(key, "v2");  
  11.         Charset charset = Charset.forName("utf-8");  
  12.         // 注意此處對key的字節轉換時,一定要和Innerhashing.hash(String)保持一致  
  13.         System.out.println(shardedJedis.get("k2").getBytes(charset));  
  14.   
  15. // Jedis的一致性hash算法已經足夠良好,程序員建議不要重寫  
  16. public class InnerHashing implements Hashing {  
  17.     static Charset charset = Charset.forName("utf-8");  
  18.   
  19.     @Override  
  20.     public long hash(String key) {  
  21.         return hash(key.getBytes(charset));  
  22.     }  
  23.   
  24.     @Override  
  25.     public long hash(byte[] key) {  
  26.         int hashcode = new HashCodeBuilder().append(key).toHashCode();  
  27.         return hashcode & 0x7FFFFFFF;  
  28.     }  
  29. }

 ShardedJedisPool & ShardedJedisPipeline

[java] view plain copy
 
  1. JedisPoolConfig config = new JedisPoolConfig();  
  2.         config.setMaxTotal(32);  
  3.         config.setMaxIdle(6);  
  4.         config.setMinIdle(0);  
  5.         config.setMaxWaitMillis(15000);  
  6.   
  7.         JedisShardInfo sd1 = new JedisShardInfo("127.0.0.1", 6379, 15000);  
  8.         sd1.setPassword("123456");  
  9.         JedisShardInfo sd2 = new JedisShardInfo("127.0.0.1", 6479, 15000);  
  10.         sd2.setPassword("123456");  
  11.         List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();  
  12.         shards.add(sd1);  
  13.         shards.add(sd2);  
  14.   
  15.         ShardedJedisPool sjp = new ShardedJedisPool(config, shards);  
  16.         ShardedJedis shardedJedis = sjp.getResource();  
  17.         try {  
  18.             System.out.println(shardedJedis.get("k2"));  
  19.   
  20.             ShardedJedisPipeline pipeline = new ShardedJedisPipeline();  
  21.             pipeline.setShardedJedis(shardedJedis);  
  22.             pipeline.set("k4", "v4");  
  23.             pipeline.set("k5", "v5");  
  24.             pipeline.get("k5");  
  25.             List<Object> all = pipeline.syncAndReturnAll();  
  26.             for (Object e : all) {  
  27.                 System.out.println(e);  
  28.             }  
  29.         } catch (Exception e) {  
  30.             e.printStackTrace();  
  31.         } finally {  
  32.             sjp.returnResource(shardedJedis);  
  33.         } 
[xml] view plain copy
 
  1. <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
  2.     <property name="maxActive" value="32"></property>  
  3.     <property name="maxIdle" value="6"></property>  
  4.     <property name="maxWait" value="15000"></property>  
  5.     <property name="minEvictableIdleTimeMillis" value="300000"></property>  
  6.     <property name="numTestsPerEvictionRun" value="3"></property>  
  7.     <property name="timeBetweenEvictionRunsMillis" value="60000"></property>  
  8.     <property name="whenExhaustedAction" value="1"></property>  
  9. </bean>  
  10. <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" destroy-method="destroy">  
  11.     <constructor-arg ref="jedisPoolConfig"></constructor-arg>  
  12.     <constructor-arg>  
  13.         <list>  
  14.             <bean class="redis.clients.jedis.JedisShardInfo">  
  15.                 <constructor-arg value="127.0.0.1"></constructor-arg>  
  16.                 <constructor-arg value="6379"></constructor-arg>  
  17.                 <property name="password" value="0123456"></property>  
  18.             </bean>  
  19.             <bean class="redis.clients.jedis.JedisShardInfo">  
  20.                 <constructor-arg value="127.0.0.1"></constructor-arg>  
  21.                 <constructor-arg value="6379"></constructor-arg>  
  22.                 <property name="password" value="0123456"></property>  
  23.             </bean>  
  24.         </list>  
  25.     </constructor-arg>  
  26. </bean>  

redis以及其他類似的網絡IO server,實現絕對意義上的自動擴容(server端)和自動探測與rebalance,是很難的,同時也有一些風險.

 

我們現在的做法也比較土:(簡而言之是:監控程序和統一配置)

1) 有個web portal系統,當一個redis實例部署好之後,就是web系統上輸入它的IP地址和探測腳本(腳本用來檢測redis的內存負載情況,存活情況).

2) 錄入之後可以將此redis"上線/下線",即將redis信息同步到zookeeper中(俗稱configserver);

3) 所有redis-client端,都接入configserver,獲取可用的redis列表;並初始化redis-client.

4) redis-client有一個額外的線程用來與configserver保持通訊,實時的跟蹤redis列表的變更.

5) 如果redis列表變更,將導致redis-client端重新調整,主要是重建"一致性hash表".

6) 重建"一致性hash表"的過程,不需要調整代碼或者重啓服務,這個和hash的設計方式有些關係.

 

簡單的來說,你可以使用任何方式(db,或者JMS訂閱)來獲取redis集羣節點的變更數據即可..對於"客戶端一致性hash表"的設計,也需要有些技巧,最好不要因爲一個節點的join或者remove,導致大面積緩存的命中失敗..

 

程序中通過合理的配置和編碼,我們可以實現寫master讀slave。

 

=

=

=

 

發佈了589 篇原創文章 · 獲贊 11 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章