springboot整合Redis后间歇性io.lettuce.core.RedisCommandTimeoutException

在springboot中引入spring-boot-starter-data-redis依赖时,默认使用的时Lettuce
产生这种问题的原因有如下两点:
1、Lettuce 自适应拓扑刷新(Adaptive updates)与定时拓扑刷新(Periodic updates) 是默认关闭的。
2、项目用了k8s做docker容器化部署,但是k8s有设置空闲连接超时就断开,所以当你从连接池拿到被断开的连接时就会报错。

springboot2.3以上版本,可添加配置解决。

    lettuce:
      cluster:
        refresh:
          adaptive: true
          period: 20

每次链接都进行自动校验

@Component
@Slf4j
public class LettuceConnectionValidConfig implements InitializingBean {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
 
    @Override
    public void afterPropertiesSet() throws Exception {
        if(redisConnectionFactory instanceof LettuceConnectionFactory){
            LettuceConnectionFactory c=(LettuceConnectionFactory)redisConnectionFactory;
            c.setValidateConnection(true);
        }
    }
}

定时任务

@Component
@Slf4j
public class LettuceConnectionValidTask   {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
 
    @Scheduled(cron="0/2 * * * * ?")
    public void task() {
        if(redisConnectionFactory instanceof LettuceConnectionFactory){
            LettuceConnectionFactory c=(LettuceConnectionFactory)redisConnectionFactory;
            c.validateConnection();
        }
    }
}

排除lettuce,采用jedis。

		
			org.springframework.boot
			spring-boot-starter-data-redis
			
				
					io.lettuce
					lettuce-core
				
			
		
		
		
			redis.clients
			jedis
		


你可能感兴趣的:(springboot,spring,boot,redis,java)