java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot中redis使用lettuce连接池经常连接超时

Springboot中redis使用lettuce连接池经常连接超时问题分析及解决

作者:夕夕夕兮

文章主要介绍了在Spring Boot项目中,使用Lettuce作为Redis客户端时遇到的问题——连接在一段时间后会自动掉线,问题的根源在于Lettuce的空闲连接处理机制,文章提供了Spring Boot 2.3及以上版本的解决方案,即通过配置解决,或者排除Lettuce并采用Jedis

环境

Springboot 2.4.4 + mysql 
redis使用 lettuce作连接池

依赖

     <!--springboot中的redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

配置

1. 问题点

项目启动后,一段时间过后redis自动掉线

io.lettuce.core.RedisCommandTimeoutException: Command timed out

2. 问题分析

这是lettuce-core的实现里,有类似心跳机制的保持长连接方式,不过心跳机制是不停的来回发心跳包直到连接不可用再去被动重新连接,而lettuce的方案是将连接池里处于空闲(idle)状态的client每隔一段时间就主动断开,然后再重新连接。

3.解决方案

如下:

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


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

结果:redis正常

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文