[轉]Jedis使用過程中踩過的那些坑

. 一個大坑若實例化 JedisShardInfo 時不設置節點名稱(name屬性),那麼當Redis節點列表的順序發生變化時,會發生鍵 rehash 現象

 

使用BTrace追蹤redis.clients.util.Sharded的實時狀態,驗證“Jedis分片機制的一致性哈希算法”實現;

發現一個致命坑:若JedisShardInfo不設置節點名稱(name屬性),那麼當Redis節點列表的順序發生變化時,會發生“鍵 rehash 現象”。見Sharded的initialize(...)方法實現:

(I) this.algo.hash("SHARD-" + i + "-NODE-" + n)

【缺點】 大坑:將節點的順序索引i作爲hash的一部分! 當節點順序被無意識地調整了,會觸發”鍵 rehash 現象”,那就杯具啦!("因節點順序調整而引發rehash"的問題)

(II) this.algo.hash(shardInfo.getName() + "*" + shardInfo.getWeight() + n)

【優點】 這樣設計避免了上面"因節點順序調整而引發rehash"的問題。

【缺點】 坑:"節點名稱+權重"必須是唯一的,否則節點會出現重疊覆蓋! 同時,"節點名稱+權重"必須不能被中途改變!

(III) 節點IP:端口號+編號

Memcached Java Client,就是採用這種策略。

【缺點】 因機房遷移等原因,可能導致節點IP發生改變!

(IIII) 唯一節點名稱+編號

較好地一致性hash策略是:唯一節點名稱+編號,不要考慮權重因素!

long hash = algo.hash(shardInfo.getName() + "*" + n)

 

所以,在配置Redis服務列表時,必須要設置節點邏輯名稱(name屬性)

 

redis.server.list=192.168.6.35:6379:Shard-01,192.168.6.36:6379:Shard-02,192.168.6.37:6379:Shard-03,192.168.6.38:6379:Shard-04

 

相關代碼如下所示:

 

 

Sharded.java代碼  收藏代碼
  1. public class Sharded<R, S extends ShardInfo<R>> {  
  2.   
  3.   public static final int DEFAULT_WEIGHT = 1;  
  4.   private TreeMap<Long, S> nodes;  
  5.   private final Hashing algo;  
  6.   private final Map<ShardInfo<R>, R> resources = new LinkedHashMap<ShardInfo<R>, R>();  
  7.   
  8.   public Sharded(List<S> shards) {  
  9.     this(shards, Hashing.MURMUR_HASH); // MD5 is really not good as we works with 64-bits not 128  
  10.   }  
  11.   
  12.   public Sharded(List<S> shards, Hashing algo) {  
  13.     this.algo = algo;  
  14.     initialize(shards);  
  15.   }  
  16.   
  17.   private void initialize(List<S> shards) {  
  18.     nodes = new TreeMap<Long, S>();  
  19.   
  20.     for (int i = 0; i != shards.size(); ++i) {  
  21.       final S shardInfo = shards.get(i);  
  22.       if (shardInfo.getName() == null) for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {  
  23.         nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo);  
  24.       }  
  25.       else for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {  
  26.         nodes.put(this.algo.hash(shardInfo.getName() + "*" + shardInfo.getWeight() + n), shardInfo);  
  27.       }  
  28.       resources.put(shardInfo, shardInfo.createResource());  
  29.     }  
  30.   }  
  31.   
  32.   ...  
  33.   
  34. }  

 

3. "Redis客戶端連接數一直降不下來"的問題

 

這個問題發生有兩方面的原因:

  1. 未正確使用對象池的空閒隊列行爲LIFO“後進先出”棧方式)
  2. 關閉集羣鏈接時異常導致連接泄漏”問題(見本文的第一個問題)

 

具體分析過程,詳見《[線上問題] "Redis客戶端連接數一直降不下來"的問題解決》。

 

2. Jedis “Socket讀取超時”導致“返回值類型錯誤

 

異常信息如下所示:

 

Redis.error.log代碼  收藏代碼
  1. [2015-02-07 09:17:47] WARN  c.f.f.b.s.r.i.CustomShardedJedisFactory -quit jedis connection for server fail: xxx.xxx.xxx.xxx:xxx  
  2. java.lang.ClassCastException: java.lang.Long cannot be cast to [B   (強制類型轉換異常)  
  3.     at redis.clients.jedis.Connection.getStatusCodeReply(Connection.java:181) ~[jedis-2.6.2.jar:na]  
  4.     at redis.clients.jedis.BinaryJedis.quit(BinaryJedis.java:136) ~[jedis-2.6.2.jar:na]  
  5.     at cn.fraudmetrix.forseti.biz.service.redis.impl.CustomShardedJedisFactory.destroyObject(CustomShardedJedisFactory.java:116) ~[forseti-biz-service-1.0-SNAPSHOT.jar:na]  
  6.     at org.apache.commons.pool2.impl.GenericObjectPool.destroy(GenericObjectPool.java:848) [commons-pool2-2.0.jar:2.0]  
  7.     at org.apache.commons.pool2.impl.GenericObjectPool.invalidateObject(GenericObjectPool.java:626) [commons-pool2-2.0.jar:2.0]  
  8.     at redis.clients.util.Pool.returnBrokenResourceObject(Pool.java:83) [jedis-2.6.2.jar:na]  
  9.     at cn.fraudmetrix.forseti.biz.service.redis.impl.CustomShardedJedisPool.returnBrokenResource(CustomShardedJedisPool.java:121) [forseti-biz-service-1.0-SNAPSHOT.jar:na]  
  10.     at cn.fraudmetrix.forseti.biz.service.redis.impl.RedisServiceImpl.zadd(RedisServiceImpl.java:337) [forseti-biz-service-1.0-SNAPSHOT.jar:na]  
  11.     at cn.fraudmetrix.forseti.biz.service.redis.impl.RedisServiceImpl.zadd(RedisServiceImpl.java:319) [forseti-biz-service-1.0-SNAPSHOT.jar:na]  
  12.     ...  
  13. [2015-02-07 09:17:47] ERROR c.f.f.b.s.r.i.RedisServiceImpl -'zadd' key fail, key: xxx, score: xxx, member: xxx  
  14.   
  15. [2015-02-07 09:17:47] ERROR c.f.f.b.s.r.i.RedisServiceImpl -java.net.SocketTimeoutException: Read timed out  
  16.   
  17. redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out    (Socket讀取超時異常)  
  18.     at redis.clients.util.RedisInputStream.ensureFill(RedisInputStream.java:201) ~[jedis-2.6.2.jar:na]     ('limit = in.read(buf);' at java.io.InputStream.read(InputStream.java:100) - 這裏出現阻塞導致"Socket讀取超時"!)  
  19.     at redis.clients.util.RedisInputStream.readByte(RedisInputStream.java:40) ~[jedis-2.6.2.jar:na]  
  20.     at redis.clients.jedis.Protocol.process(Protocol.java:128) ~[jedis-2.6.2.jar:na]  
  21.     at redis.clients.jedis.Protocol.read(Protocol.java:192) ~[jedis-2.6.2.jar:na]  
  22.     at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:282) ~[jedis-2.6.2.jar:na]  
  23.     at redis.clients.jedis.Connection.getIntegerReply(Connection.java:207) ~[jedis-2.6.2.jar:na]  
  24.     at redis.clients.jedis.Jedis.zadd(Jedis.java:1293) ~[jedis-2.6.2.jar:na]  
  25.     at redis.clients.jedis.ShardedJedis.zadd(ShardedJedis.java:364) ~[jedis-2.6.2.jar:na]  
  26.     at cn.fraudmetrix.forseti.biz.service.redis.impl.RedisServiceImpl.zadd(RedisServiceImpl.java:328) [forseti-biz-service-1.0-SNAPSHOT.jar:na]  
  27.     at cn.fraudmetrix.forseti.biz.service.redis.impl.RedisServiceImpl.zadd(RedisServiceImpl.java:319) [forseti-biz-service-1.0-SNAPSHOT.jar:na]  
  28.     ...  
  29. Caused by: java.net.SocketTimeoutException: Read timed out  
  30.     at java.net.SocketInputStream.socketRead0(Native Method) ~[na:1.7.0_51]  
  31.     at java.net.SocketInputStream.read(SocketInputStream.java:152) ~[na:1.7.0_51]  
  32.     at java.net.SocketInputStream.read(SocketInputStream.java:122) ~[na:1.7.0_51]  
  33.     at java.net.SocketInputStream.read(SocketInputStream.java:108) ~[na:1.7.0_51]  
  34.     at redis.clients.util.RedisInputStream.ensureFill(RedisInputStream.java:195) ~[jedis-2.6.2.jar:na]  
  35.     ... 38 common frames omitted  
 

 

從異常信息來看,首先是在'zadd'操作時出現"Socket讀取超時異常",具體異常信息"JedisConnectionException: java.net.SocketTimeoutException: Read timed out"。

出現異常後,會銷燬這個阻塞的Jedis連接池對象(CustomShardedJedisPool.returnBrokenResource(CustomShardedJedisPool.java:121)),但在請求Redis服務端關閉連接時,出現"強制類型轉換異常",具體異常信息"ClassCastException: java.lang.Long cannot be cast to [B"。

 

這個問題已經有前輩遇到過了,其解釋:

查看 Jedis 源碼發現它的Connection中對網絡輸出流做了一個封裝(RedisInputStream),其中自建了一個buffer。當發生異常的時候,這個buffer裏還殘存着上次沒有發送或者發送不完整的命令。這個時候沒有做處理,直接將該連接返回到連接池,那麼重用該連接執行下次命令的時候,就會將上次沒有發送的命令一起發送過去,所以纔會出現上面的錯誤“返回值類型不對”

所以,正確的寫法應該是:在發送異常的時候,銷燬這個連接,不能再重用! 

 

參考自:

 

1. CustomShardedJedisFactory.destroyObject(PooledObject<ShardedJedis> pooledShardedJedis) 存在“客戶端連接泄露”問題

 

異常信息如下所示:

 

Redis.error.log代碼  收藏代碼
  1. [2015-01-28 15:33:51] ERROR c.f.f.b.s.r.i.RedisServiceImpl -ShardedJedis close fail     
  2.   
  3. redis.clients.jedis.exceptions.JedisException: Could not return the resource to the pool   
  4. at redis.clients.util.Pool.returnBrokenResourceObject(Pool.java:85) ~[jedis-2.6.2.jar:na]         
  5. at cn.fraudmetrix.forseti.biz.service.redis.impl.CustomShardedJedisPool.returnBrokenResource(CustomShardedJedisPool.java:120) ~[forseti-biz-service-1.0-SNAPSHOT.jar:na]         
  6. at cn.fraudmetrix.forseti.biz.service.redis.impl.CustomShardedJedisPool.returnBrokenResource(CustomShardedJedisPool.java:26) ~[forseti-biz-service-1.0-SNAPSHOT.jar:na]         
  7. at redis.clients.jedis.ShardedJedis.close(ShardedJedis.java:638) ~[jedis-2.6.2.jar:na]         
  8. at cn.fraudmetrix.forseti.biz.service.redis.impl.RedisServiceImpl.close(RedisServiceImpl.java:90) [forseti-biz-service-1.0-SNAPSHOT.jar:na]         
  9. at cn.fraudmetrix.forseti.biz.service.redis.impl.RedisServiceImpl.zadd(RedisServiceImpl.java:380) [forseti-biz-service-1.0-SNAPSHOT.jar:na]         
  10. at cn.fraudmetrix.forseti.biz.service.redis.impl.RedisServiceImpl.zadd(RedisServiceImpl.java:346) [forseti-biz-service-1.0-SNAPSHOT.jar:na]         
  11. ...      
  12. at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [na:1.7.0_51]         
  13. at java.util.concurrent.FutureTask.run(FutureTask.java:262) [na:1.7.0_51]         
  14. at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_51]  
  15. at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_51]  
  16. at java.lang.Thread.run(Thread.java:744) [na:1.7.0_51]         
  17. Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to [B   
  18. at redis.clients.jedis.Connection.getStatusCodeReply(Connection.java:181) ~[jedis-2.6.2.jar:na]         
  19. at redis.clients.jedis.BinaryJedis.quit(BinaryJedis.java:136) ~[jedis-2.6.2.jar:na]         
  20. at redis.clients.jedis.BinaryShardedJedis.disconnect(BinaryShardedJedis.java:35) ~[jedis-2.6.2.jar:na]  
  21. at cn.fraudmetrix.forseti.biz.service.redis.impl.CustomShardedJedisFactory.destroyObject(CustomShardedJedisFactory.java:106) ~[forseti-biz-service-1.0-SNAPSHOT.jar:na]         
  22. at org.apache.commons.pool2.impl.GenericObjectPool.destroy(GenericObjectPool.java:848) ~[commons-pool2-2.0.jar:2.0]         
  23. at org.apache.commons.pool2.impl.GenericObjectPool.invalidateObject(GenericObjectPool.java:626) ~[commons-pool2-2.0.jar:2.0]         
  24. at redis.clients.util.Pool.returnBrokenResourceObject(Pool.java:83) ~[jedis-2.6.2.jar:na]         
  25. ... 37 common frames omitted  

 

 

從異常信息來看,是由於應用程序無法捕獲運行時的強制類型轉換異常(“java.lang.ClassCastException: java.lang.Long cannot be cast to [B”)導致關閉操作異常中斷,問題的根源代碼位於“BinaryShardedJedis.disconnect(BinaryShardedJedis.java:35)

CustomShardedJedisFactory.destroyObject(CustomShardedJedisFactory.java:106)”。

 

原實現代碼只捕獲了 JedisConnectionException 異常,如下所示:

 

 

Customshardedjedisfactory.java代碼  收藏代碼
  1. public void destroyObject(PooledObject<ShardedJedis> pooledShardedJedis) throws Exception {  
  2.     final ShardedJedis shardedJedis = pooledShardedJedis.getObject();  
  3.   
  4.     shardedJedis.disconnect(); // "鏈接資源"無法被釋放,存在泄露  
  5. }  

 

 

Binaryshardedjedis.java代碼  收藏代碼
  1. public void disconnect() {  
  2.   for (Jedis jedis : getAllShards()) {  
  3.     try {  
  4.       jedis.quit();  
  5.     } catch (JedisConnectionException e) {  
  6.       // ignore the exception node, so that all other normal nodes can release all connections.  
  7.     }  
  8.     try {  
  9.       jedis.disconnect();  
  10.     } catch (JedisConnectionException e) {  
  11.       // ignore the exception node, so that all other normal nodes can release all connections.  
  12.     }  
  13.   }  
  14. }  

 

修復後代碼捕獲了所有的 Exception,就不存在釋放鏈接時由於異常未捕獲而導致鏈接釋放中斷。如下所示:

 

Customshardedjedisfactory.java代碼  收藏代碼
  1. public void destroyObject(PooledObject<ShardedJedis> pooledShardedJedis) throws Exception {  
  2.     final ShardedJedis shardedJedis = pooledShardedJedis.getObject();  
  3.   
  4.     // shardedJedis.disconnect(); // "鏈接資源"無法被釋放,存在泄露  
  5.     for (Jedis jedis : shardedJedis.getAllShards()) {  
  6.         try {  
  7.             // 1. 請求服務端關閉連接  
  8.             jedis.quit();  
  9.         } catch (Exception e) {  
  10.             // ignore the exception node, so that all other normal nodes can release all connections.  
  11.   
  12.             // java.lang.ClassCastException: java.lang.Long cannot be cast to [B  
  13.             // (zadd/zcard 返回 long 類型,而 quit 返回 string 類型。從這裏看,上一次的請求結果並未讀取)  
  14.             logger.warn("quit jedis connection for server fail: " + toServerString(jedis), e);  
  15.         }  
  16.   
  17.         try {  
  18.             // 2. 客戶端主動關閉連接  
  19.             jedis.disconnect();  
  20.         } catch (Exception e) {  
  21.             // ignore the exception node, so that all other normal nodes can release all connections.  
  22.   
  23.             logger.warn("disconnect jedis connection fail: " + toServerString(jedis), e);  
  24.         }  
  25.     }  

  1. }  

轉:http://bert82503.iteye.com/blog/2184225

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章