Redis空闲一段时候后报错

问题描述

使用spring-data-redis后,如果应用长达一段时间没访问,新的请求使用redis时,可能会报错:io.lettuce.core.RedisException: java.io.IOException: 远程主机强迫关闭了一个现有的连接

解决方案

  1. 修改项目配置
# spring默认使用lettuce,详情参见:LettuceConnectionConfiguration
spring.redis.client-type=lettuce
spring.redis.lettuce.pool.minIdle=1
spring.redis.lettuce.pool.maxIdle=8
# 5分钟执行一次
spring.redis.lettuce.pool.timeBetweenEvictionRuns=PT2M
spring.redis.lettuce.pool.enabled=true
spring.redis.lettuce.shutdownTimeout=PT0.1S
  1. 修改redis.conf(可能不用改)
tcp-keepalive 60
  1. 修改LettuceConnectionFactory的shareNativeConnection参数
// 新增一个配置类,在创建RedisTemplate之前,修改LettuceConnectionFactory的shareNativeConnection参数
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "spring.redis.client-type", havingValue = "lettuce", matchIfMissing = true)
public class RedisAutoConfiguration {

    @Bean
        public RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        redisConnectionFactory.setShareNativeConnection(false);
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        redisConnectionFactory.setShareNativeConnection(false);
        return new StringRedisTemplate(redisConnectionFactory);
    }
}

// LettuceConnectionFactory.java中的源码
// 如果不修改sharedConnection为false, lettuce根本没使用自己配置的连接池
protected StatefulRedisConnection<byte[], byte[]> getSharedConnection() {
	return shareNativeConnection && !isClusterAware()
			? (StatefulRedisConnection) getOrCreateSharedConnection().getConnection()
			: null;
}
public RedisConnection getConnection() {
	connection = doCreateLettuceConnection(getSharedConnection(), connectionProvider, getTimeout(), getDatabase());
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值