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


 

一、背景

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

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

 

二、解決

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

1、enableTransactionSupport = false 。此時redis不支持事物。RedisTemplate會在使用完了之后自動釋放連接;

2、enableTransactionSupport = true 。此時redis支持事物。RedisTemplate是不會主動釋放連接的,需要手動釋放連接,此問題可以參考這篇文檔:Sping Data Redis 使用事務時,不關閉連接的問題

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

 

三、附錄

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

 1、Jedis常見異常匯總

 2、JedisPool資源池優化

 

 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM