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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值