spring使用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资源池优化

 

 


posted @ 2019-01-14 17:54  Erneste  阅读(13454)  评论(0编辑  收藏  举报