spring整合redis使用RedisTemplate的坑Could not get a resource from the pool

 

1、背景java

  項目中使用spring框架整合redis,使用框架封裝的RedisTemplate來實現數據的增刪改查,項目上線後,我發現運行一段時間後,會出現異常Could not get a resource from the pool。起初我是以爲redis的最大鏈接數不夠,因此一味地增大最大鏈接數,試了幾回,發現仍是報異常:Could not get a resource from the pool。可是看到鏈接池中明顯有連接,何況此問題通常是資源池的鏈接數大於設置的最大鏈接數纔出現。最後懷疑是沒有釋放鏈接。so網上搜,解決了這個問題。redis

Caused by: redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool
	at redis.clients.util.Pool.getResource(Pool.java:51)
	at redis.clients.jedis.JedisPool.getResource(JedisPool.java:226)
	at redis.clients.jedis.JedisPool.getResource(JedisPool.java:16)
	at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:191)
	... 86 more
Caused by: java.util.NoSuchElementException: Timeout waiting for idle object
	at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:449)
	at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
	at redis.clients.util.Pool.getResource(Pool.java:49)
	... 89 more

 

2、解決spring

問題的關鍵在於redis的配置文件中enableTransactionSupport的設置。apache

一、enableTransactionSupport = false 。此時redis不支持事物。RedisTemplate會在使用完了以後自動釋放鏈接;框架

二、enableTransactionSupport = true 。此時redis支持事物。RedisTemplate是不會主動釋放鏈接的,須要手動釋放鏈接,此問題能夠參考這篇文檔:Sping Data Redis 使用事務時,不關閉鏈接的問題fetch

redisTemplate.exec();
RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());

 

3、附錄優化

附上阿里雲redis的常見異常文檔阿里雲

 一、Jedis常見異常彙總spa

 二、JedisPool資源池優化.net

相關文章
相關標籤/搜索