一、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?)。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLyFGdz9lbvNWavw1cldWYtl2Lc12bj5SZ5VGdp5SesV2dvw1LcpDc0RHaiojIsJye.png)
public interface Hashing {
public static final Hashing MURMUR_HASH = new MurmurHash();
public ThreadLocal<MessageDigest> md5Holder = new ThreadLocal<MessageDigest>();
// 基于MD5的一緻性hash算法實作
public static final Hashing MD5 = new Hashing() {
public long hash(String key) {
return hash(SafeEncoder.encode(key));
}
public long hash(byte[] key) {
try {
if (md5Holder.get() == null) {
md5Holder.set(MessageDigest.getInstance("MD5"));
}
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("++++ no md5 algorythm found");
}
MessageDigest md5 = md5Holder.get();
md5.reset();
md5.update(key);
byte[] bKey = md5.digest(); // 獲得MD5位元組序列
// 前四個位元組作為計算參數,最終獲得一個32位int值.
// 此種計算方式,能夠確定key的hash值更加“随即”/“離散”
// 如果hash值過于密集,不利于一緻性hash的實作(特别是有“虛拟節點”設計時)
long res = ((long) (bKey[3] & 0xFF) << 24) | ((long) (bKey[2] & 0xFF) << 16)
| ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF);
return res;
};
public long hash(String key);
public long hash(byte[] key);
}
node建構過程:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLyFGdz9lbvNWavw1cldWYtl2Lc12bj5SZ5VGdp5SesV2dvw1LcpDc0RHaiojIsJye.png)
//shards清單為用戶端提供了所有redis-server配置資訊,包括:ip,port,weight,name
//其中weight為權重,将直接決定“虛拟節點”的“比例”(密度),權重越高,在存儲是被hash命中的機率越高
//--其上存儲的資料越多。
//其中name為“節點名稱”,jedis使用name作為“節點hash值”的一個計算參數。
//---
//一緻性hash算法,要求每個“虛拟節點”必須具備“hash值”,每個實際的server可以有多個“虛拟節點”(API級别)
//其中虛拟節點的個數= “邏輯區間長度” * weight,每個server的“虛拟節點”将會以“hash”的方式分布在全局區域中
//全局區域總長為2^32.每個“虛拟節點”以hash值的方式映射在全局區域中。
// 環形:0-->vnode1(:1230)-->vnode2(:2800)-->vnode3(400000)---2^32-->0
//所有的“虛拟節點”将按照其”節點hash“順序排列(正序/反序均可),是以相鄰兩個“虛拟節點”之間必有hash值差,
//那麼此內插補點,即為前一個(或者後一個,根據實作而定)“虛拟節點”所負載的資料hash值區間。
//比如hash值為“2000”的資料将會被vnode1所接受。
private void initialize(List<S> shards) {
nodes = new TreeMap<Long, S>();//虛拟節點,采取TreeMap存儲:排序,二叉樹
for (int i = 0; i != shards.size(); ++i) {
final S shardInfo = shards.get(i);
if (shardInfo.getName() == null)
//當沒有設定“name”是,将“SHARD-NODE”作為“虛拟節點”hash值計算的參數
//"邏輯區間步長"為160,為什麼呢??
//最終多個server的“虛拟節點”将會交錯布局,不一定非常均勻。
for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo);
}
else
nodes.put(this.algo.hash(shardInfo.getName() + "*" + shardInfo.getWeight() + n), shardInfo);
resources.put(shardInfo, shardInfo.createResource());
node選擇方式:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLyFGdz9lbvNWavw1cldWYtl2Lc12bj5SZ5VGdp5SesV2dvw1LcpDc0RHaiojIsJye.png)
public R getShard(String key) {
return resources.get(getShardInfo(key));
//here:
public S getShardInfo(byte[] key) {
//擷取>=key的“虛拟節點”的清單
SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));
//如果不存在“虛拟節點”,則将傳回首節點。
if (tail.size() == 0) {
return nodes.get(nodes.firstKey());
//如果存在,則傳回符合(>=key)條件的“虛拟節點”的第一個節點
return tail.get(tail.firstKey());
Jedis sharding預設的一緻性hash算法比較适合cache-only的情景,不太适合資料持久化情況。在持久存儲情況下,我們可以使用“強hash”分片,需要重寫hash算法(參加後面的InnerHashing)。強hash算法下,如果某個虛拟節點所在的實體節點故障,将導緻資料無法通路,即無法從虛拟節點清單中删除失效的server。
二、API
ShardedJedis
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLyFGdz9lbvNWavw1cldWYtl2Lc12bj5SZ5VGdp5SesV2dvw1LcpDc0RHaiojIsJye.png)
JedisShardInfo sd1 = new JedisShardInfo("127.0.0.1", 6379, 15000);
sd1.setPassword("123456");
JedisShardInfo sd2 = new JedisShardInfo("127.0.0.1", 6479, 15000);
sd2.setPassword("123456");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(sd1);
shards.add(sd2);
ShardedJedis shardedJedis = new ShardedJedis(shards, new InnerHashing());
String key = "k2sdjowejjroer3";
shardedJedis.set(key, "v2");
Charset charset = Charset.forName("utf-8");
// 注意此處對key的位元組轉換時,一定要和Innerhashing.hash(String)保持一緻
System.out.println(shardedJedis.get("k2").getBytes(charset));
// Jedis的一緻性hash算法已經足夠良好,程式員建議不要重寫
public class InnerHashing implements Hashing {
static Charset charset = Charset.forName("utf-8");
@Override
return hash(key.getBytes(charset));
int hashcode = new HashCodeBuilder().append(key).toHashCode();
return hashcode & 0x7FFFFFFF;
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLyFGdz9lbvNWavw1cldWYtl2Lc12bj5SZ5VGdp5SesV2dvw1LcpDc0RHaiojIsJye.png)
<bean id="shardedJedis" class="redis.clients.jedis.ShardedJedis">
<constructor-arg>
<list>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg value="127.0.0.1"></constructor-arg>
<constructor-arg value="6379"></constructor-arg>
<property name="password" value="0123456"></property>
</bean>
</list>
</constructor-arg>
</bean>
ShardedJedisPool & ShardedJedisPipeline
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLyFGdz9lbvNWavw1cldWYtl2Lc12bj5SZ5VGdp5SesV2dvw1LcpDc0RHaiojIsJye.png)
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(32);
config.setMaxIdle(6);
config.setMinIdle(0);
config.setMaxWaitMillis(15000);
JedisShardInfo sd1 = new JedisShardInfo("127.0.0.1", 6379, 15000);
sd1.setPassword("123456");
JedisShardInfo sd2 = new JedisShardInfo("127.0.0.1", 6479, 15000);
sd2.setPassword("123456");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(sd1);
shards.add(sd2);
ShardedJedisPool sjp = new ShardedJedisPool(config, shards);
ShardedJedis shardedJedis = sjp.getResource();
try {
System.out.println(shardedJedis.get("k2"));
ShardedJedisPipeline pipeline = new ShardedJedisPipeline();
pipeline.setShardedJedis(shardedJedis);
pipeline.set("k4", "v4");
pipeline.set("k5", "v5");
pipeline.get("k5");
List<Object> all = pipeline.syncAndReturnAll();
for (Object e : all) {
System.out.println(e);
} catch (Exception e) {
e.printStackTrace();
} finally {
sjp.returnResource(shardedJedis);
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLyFGdz9lbvNWavw1cldWYtl2Lc12bj5SZ5VGdp5SesV2dvw1LcpDc0RHaiojIsJye.png)
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxActive" value="32"></property>
<property name="maxIdle" value="6"></property>
<property name="maxWait" value="15000"></property>
<property name="minEvictableIdleTimeMillis" value="300000"></property>
<property name="numTestsPerEvictionRun" value="3"></property>
<property name="timeBetweenEvictionRunsMillis" value="60000"></property>
<property name="whenExhaustedAction" value="1"></property>
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" destroy-method="destroy">
<constructor-arg ref="jedisPoolConfig"></constructor-arg>
Something:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLyFGdz9lbvNWavw1cldWYtl2Lc12bj5SZ5VGdp5SesV2dvw1LcpDc0RHaiojIsJye.png)
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。
本人通過檢視公司應用系統的監控表明,redis幾乎保持 set 2ms get 1ms, sql最快時 count 2ms select 3ms add/update 5ms
原文連結:[http://wely.iteye.com/blog/2275944]