今天一个程序,关闭 jedis 时报错 JedisException:Could not return the resource to the pool 。。。IllegalStateException: Invalidated object not currently part of this pool
关闭 jedis 是这样写的:
@Autowired private RedisUtil redisUtil; Jedis jedis = redisUtil.getJedis(); 。。。 } finally { if ( jedis != null ) { jedis.close(); // 报错 } }网上说是多线程创建 jedisPool 导致的问题,参考:
https://my.oschina.net/zhuguowei/blog/406807
http://bert82503.iteye.com/blog/2184225
http://www.voidcn.com/article/p-esrbxogl-dr.html
http://code.taobao.org/p/moonx/diff/6/trunk/springside4/modules/redis/src/main/java/org/springside/modules/nosql
解决方法,在 redisUtil 里加上这三个方法:
// 关闭 jedis public void closeJedis( Jedis jedis ) { try { if ( jedis != null ) { if ( jedis != null ) { jedis.close(); } } } catch (Exception e) { closeBrokenResource( jedis ); } } /** * Return jedis connection to the pool, call different return methods depends on whether the connection is broken */ public void closeBrokenResource( Jedis jedis ) { try { jedisPool.returnBrokenResource( jedis ); } catch ( Exception e ) { destroyJedis( jedis ); } } /** * 在 Jedis Pool 以外强行销毁 Jedis */ public static void destroyJedis( Jedis jedis ) { if ( jedis != null ) { try { jedis.quit(); } catch ( Exception e ) { print( ">>> RedisUtil-jedis.quit() : " + e ); //e.printStackTrace(); } try { jedis.disconnect(); } catch ( Exception e ) { print( ">>> RedisUtil-jedis.disconnect() : " + e ); //e.printStackTrace(); } } }然后,在程序里,不用 jedis.close() 关闭 jedis,而是调用注入的 redisUtil 的 closeJedis( jedis ) 方法:
} finally { redisUtil.closeJedis( jedis ); }
-----------------------------
2018-6-23 上午 修改了一下 destroyJedis( Jedis jedis ) 这个方法