在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。

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
			<exclusions>
				<exclusion>
					<groupId>io.lettuce</groupId>
					<artifactId>lettuce-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</dependency>


Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐