You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

Spring整合Redis首次调用出现Could not return the resource to the pool错误

解决Spring整合Redis首次调用报错"Could not return the resource to the pool"的问题

我之前碰到过几乎一模一样的问题,这个错误本质是Jedis连接池在回收资源时发现资源已经不在池内,结合你的配置和堆栈信息,通常和版本兼容性连接池配置缺失或者序列化逻辑异常有关,给你几个针对性的解决办法:

1. 核对Spring Data Redis与Jedis的版本兼容性

不同版本的Spring Data Redis和Jedis之间存在严格的依赖匹配要求,版本不匹配会直接导致连接池的资源管理逻辑出现冲突:

  • 若使用Spring Data Redis 1.8.x,建议搭配Jedis 2.9.x版本
  • 若使用Spring Data Redis 2.x+,则需要Jedis 3.x及以上版本
    你可以对照官方的版本矩阵调整依赖,确保两者版本完全兼容。

2. 显式配置Jedis连接池参数

你的当前配置仅开启了连接池但未设置具体参数,首次请求时连接池的初始化逻辑可能存在隐性问题。建议添加JedisPoolConfig的详细配置:

<!-- 配置Jedis连接池核心参数 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <!-- 最大连接数 -->
    <property name="maxTotal" value="100"/>
    <!-- 最大空闲连接数 -->
    <property name="maxIdle" value="20"/>
    <!-- 最小空闲连接数 -->
    <property name="minIdle" value="5"/>
    <!-- 获取连接时自动验证有效性 -->
    <property name="testOnBorrow" value="true"/>
    <!-- 归还连接时自动验证有效性 -->
    <property name="testOnReturn" value="true"/>
    <!-- 定期清理空闲连接的间隔时间 -->
    <property name="timeBetweenEvictionRunsMillis" value="30000"/>
</bean>

<!-- 更新JedisConnectionFactory,引用连接池配置 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" 
      p:host-name="172.17.0.2" 
      p:use-pool="true"
      p:poolConfig-ref="jedisPoolConfig" />

其中testOnBorrowtestOnReturn可以确保连接在获取和归还时都经过有效性校验,从根源避免无效连接被放回池内引发后续错误。

3. 为RedisTemplate配置序列化器

你的RedisTemplate未指定序列化器,默认使用的JdkSerializationRedisSerializer在序列化复杂对象(比如你的MyAwesomeDTO)时,可能会在首次调用时抛出隐性异常,间接导致连接池资源回收失败。建议配置可读性更好、更稳定的序列化器:

<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" 
      p:connection-factory-ref="jedisConnectionFactory">
    <!-- Key使用String序列化,保证可读性 -->
    <property name="keySerializer">
        <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    </property>
    <!-- Value使用JSON序列化,避免JDK序列化的兼容性问题 -->
    <property name="valueSerializer">
        <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
    </property>
    <!-- Hash类型的Key和Value同步配置序列化 -->
    <property name="hashKeySerializer">
        <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    </property>
    <property name="hashValueSerializer">
        <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
    </property>
</bean>

4. 验证Redis服务端的连接稳定性

首次调用失败也可能是网络波动或Redis服务端临时响应异常导致的,你可以在应用启动前先通过jedis-cli工具测试与Redis服务端的连接,确保网络通畅、服务正常运行。

修改配置后重启应用,多次调用getSomeResult方法,应该就能解决首次调用报错的问题了。

内容的提问来源于stack exchange,提问作者vtokmak

火山引擎 最新活动