使用Jedis線程池returnResource異常注意事項
在線上環(huán)境發(fā)現(xiàn)了一個工作線程異常終止
看日志先是一些SocketTimeoutException,然后突然有一個ClassCastException
redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out ... java.lang.ClassCastException: [B cannot be cast to java.lang.Long at redis.clients.jedis.Connection.getIntegerReply(Connection.java:208) at redis.clients.jedis.Jedis.sismember(Jedis.java:1307)
經(jīng)過在本地人工模擬網(wǎng)絡(luò)異常的情境,最終復(fù)現(xiàn)了線上的這一異常。
又經(jīng)過深入分析(提出假設(shè)-->驗證假設(shè)),最終找出了導(dǎo)致這一問題的原因。
見如下示例代碼
JedisPool pool = ...; Jedis jedis = pool.getResource(); String value = jedis.get("foo"); System.out.println("Make SocketTimeoutException"); System.in.read(); //等待制造SocketTimeoutException try { value = jedis.get("foo"); System.out.println(value); } catch (JedisConnectionException e) { e.printStackTrace(); } System.out.println("Recover from SocketTimeoutException"); System.in.read(); //等待恢復(fù) Thread.sleep(5000); // 繼續(xù)休眠一段時間 等待網(wǎng)絡(luò)完全恢復(fù) boolean isMember = jedis.sismember("urls", "baidu.com");
以及日志輸出
bar Make SocketTimeoutException redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out Recover from SocketTimeoutException at redis.clients.util.RedisInputStream.ensureFill(RedisInputStream.java:210) at redis.clients.util.RedisInputStream.readByte(RedisInputStream.java:47) at redis.clients.jedis.Protocol.process(Protocol.java:131) at redis.clients.jedis.Protocol.read(Protocol.java:196) at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:283) at redis.clients.jedis.Connection.getBinaryBulkReply(Connection.java:202) at redis.clients.jedis.Connection.getBulkReply(Connection.java:191) at redis.clients.jedis.Jedis.get(Jedis.java:101) at com.tcl.recipevideohunter.JedisTest.main(JedisTest.java:23) Caused by: java.net.SocketTimeoutException: Read timed out at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:152) at java.net.SocketInputStream.read(SocketInputStream.java:122) at java.net.SocketInputStream.read(SocketInputStream.java:108) at redis.clients.util.RedisInputStream.ensureFill(RedisInputStream.java:204) ... 8 more Exception in thread "main" java.lang.ClassCastException: [B cannot be cast to java.lang.Long at redis.clients.jedis.Connection.getIntegerReply(Connection.java:208) at redis.clients.jedis.Jedis.sismember(Jedis.java:1307) at com.tcl.recipevideohunter.JedisTest.main(JedisTest.java:32)
分析
等執(zhí)行第二遍的get("foo")時,網(wǎng)絡(luò)超時,并未實際發(fā)送 get foo 命令,等執(zhí)行sismember時,網(wǎng)絡(luò)已恢復(fù)正常,并且是同一個jedis實例,于是將之前的get foo命令(已在輸出流緩存中)一并發(fā)送。
執(zhí)行順序如下所示
127.0.0.1:9379> get foo"bar"127.0.0.1:9379> sismember urls baidu.com(integer) 1127.0.0.1:9379> get foo "bar" 127.0.0.1:9379> sismember urls baidu.com (integer) 1
故在上述示例代碼中最后的sismember得到的結(jié)果是get foo的結(jié)果,即一個字符串,而sismember需要的是一個Long型,故導(dǎo)致了ClassCastException。
執(zhí)行redis的邏輯
為什么線上會出現(xiàn)這一問題呢?原因是其執(zhí)行redis的邏輯類似這樣:
while(true){ Jedis jedis = null; try { jedis = pool.getResource(); //some redis operation here. } catch (Exception e) { logger.error(e); } finally { pool.returnResource(jedis); } }
因若是網(wǎng)絡(luò)異常的話,pool.returnResource(jedis)仍能成功執(zhí)行,即能將其返回到池中(這時jedis并不為空)。等網(wǎng)絡(luò)恢復(fù)后,并是多線程環(huán)境,導(dǎo)致后續(xù)其他某個線程獲得了同一個Jedis實例(pool.getResource()),
若該線程中的jedis操作返回類型與該jedis實例在網(wǎng)絡(luò)異常期間第一條未執(zhí)行成功的jedis操作的返回類型不匹配(如一個是get,一個是sismember),則就會出現(xiàn)ClassCastException異常。
這還算幸運的,若返回的是同一類型的話(如lpop("queue_order_pay_failed"),lpop("queue_order_pay_success")),那我真不敢想象。
如在上述示例代碼中的sismember前插入一get("nonexist-key")(redis中不存在該key,即應(yīng)該返回空).
value = jedis.get("nonexist-key"); System.out.println(value); boolean isMember = jedis.sismember("urls", "baidu.com"); System.out.println(isMember);
實際的日志輸出為
bar Exception in thread "main" java.lang.NullPointerException at redis.clients.jedis.Jedis.sismember(Jedis.java:1307) at com.tcl.recipevideohunter.JedisTest.main(JedisTest.java:37)
分析:
get("nonexist-key")得到是之前的get("foo")的結(jié)果, 而sismember得到的是get("nonexist-key")的結(jié)果,而get("nonexist-key")返回為空,于是這時是報空指針異常了.
解決方法:
不能不管什么情況都一律使用returnResource。更健壯可靠以及優(yōu)雅的處理方式如下所示:
while(true){ Jedis jedis = null; boolean broken = false; try { jedis = jedisPool.getResource(); return jedisAction.action(jedis); //模板方法 } catch (JedisException e) { broken = handleJedisException(e); throw e; } finally { closeResource(jedis, broken); } } /** * Handle jedisException, write log and return whether the connection is broken. */ protected boolean handleJedisException(JedisException jedisException) { if (jedisException instanceof JedisConnectionException) { logger.error("Redis connection " + jedisPool.getAddress() + " lost.", jedisException); } else if (jedisException instanceof JedisDataException) { if ((jedisException.getMessage() != null) && (jedisException.getMessage().indexOf("READONLY") != -1)) { logger.error("Redis connection " + jedisPool.getAddress() + " are read-only slave.", jedisException); } else { // dataException, isBroken=false return false; } } else { logger.error("Jedis exception happen.", jedisException); } return true; } /** * Return jedis connection to the pool, call different return methods depends on the conectionBroken status. */ protected void closeResource(Jedis jedis, boolean conectionBroken) { try { if (conectionBroken) { jedisPool.returnBrokenResource(jedis); } else { jedisPool.returnResource(jedis); } } catch (Exception e) { logger.error("return back jedis failed, will fore close the jedis.", e); JedisUtils.destroyJedis(jedis); } }
補充
Ubuntu本地模擬訪問redis網(wǎng)絡(luò)超時:
sudo iptables -A INPUT -p tcp --dport 6379 -j DROP
恢復(fù)網(wǎng)絡(luò):
sudo iptables -F
補充:
若jedis操作邏輯類似下面所示的話,
Jedis jedis = null; try { jedis = jedisSentinelPool.getResource(); return jedis.get(key); }catch(JedisConnectionException e) { jedisSentinelPool.returnBrokenResource(jedis); logger.error("", e); throw e; }catch (Exception e) { logger.error("", e); throw e; } finally { jedisSentinelPool.returnResource(jedis); }
若一旦發(fā)生了JedisConnectionException,如網(wǎng)絡(luò)異常,會先執(zhí)行returnBrokenResource,這時jedis已被destroy了。然后進入了finally,再一次執(zhí)行returnResource,這時會報錯:
redis.clients.jedis.exceptions.JedisException: Could not return the resource to the pool at redis.clients.util.Pool.returnResourceObject(Pool.java:65) at redis.clients.jedis.JedisSentinelPool.returnResource(JedisSentinelPool.java:221)
臨時解決方法
jedisSentinelPool.returnBrokenResource(jedis); jedis=null; //這時不會實際執(zhí)行returnResource中的相關(guān)動作了
但不建議這樣處理,更嚴(yán)謹(jǐn)?shù)尼尫刨Y源方法見前文所述。
以上就是使用Jedis線程池returnResource異常注意事項的詳細(xì)內(nèi)容,更多關(guān)于Jedis線程池returnResource異常的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
高并發(fā)下Redis如何保持?jǐn)?shù)據(jù)一致性(避免讀后寫)
本文主要介紹了高并發(fā)下Redis如何保持?jǐn)?shù)據(jù)一致性(避免讀后寫),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03redis與memcached的區(qū)別_動力節(jié)點Java學(xué)院整理
Memcached是以LiveJurnal旗下Danga Interactive公司的Bard Fitzpatric為首開發(fā)的高性能分布式內(nèi)存緩存服務(wù)器。那么redis與memcached有什么區(qū)別呢?下面小編給大家介紹下redis與memcached的區(qū)別,感興趣的朋友參考下吧2017-08-08分布式鎖為什么要選擇Zookeeper而不是Redis?看完這篇你就明白了
Zookeeper的機制可以保證分布式鎖實現(xiàn)業(yè)務(wù)代碼簡單,成本低,Redis如果要解決分布式鎖的問題,對于一些復(fù)雜的情況,很難解決,成本較高,這篇文章重點給大家介紹分布式鎖選擇Zookeeper 而不是Redis的理由,一起看看吧2021-05-05壓縮列表犧牲速度來節(jié)省內(nèi)存,Redis是膨脹了嗎
這篇文章主要給大家解釋了Redis 當(dāng)中的 ziplist(壓縮列表)犧牲速度來節(jié)省內(nèi)存的原因,希望大家能夠喜歡2021-02-02