假设服务端没有问题,配置没有问题。那就是SpringBoot的Redis的Lettuce出了问题, 没有空闲连接,当连接上来之后,一切正常,隔一段时间没有连接的时候,就会Spring就瘵连接池关了连接切断了,然后页面再一次请求连接的时候,客户端再重新请求连接到服务器。所以才会出现 这样的问题。才会出现 连接超时
- 配置类
@Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuce) { //设置序列化 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置redisTemplate RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(lettuce); RedisSerializer<String> stringSerializer = new StringRedisSerializer(); // key序列化 redisTemplate.setKeySerializer(stringSerializer); // value序列化 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // Hash key序列化 redisTemplate.setHashKeySerializer(stringSerializer); // Hash value序列化 redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
解决方案:
lettuce提供了校验连接的方法,lettuce提供了校验连接的方法 只是默认没开启 开启的话是每次获取连接都会校验。可以定时校验来解决 或者开启获取连接的校验
- 定时校验来解决
/** * 每隔2秒校验异常lettuce连接是否正常,解决长期空闲lettuce连接关闭但是netty不能及时监控到的问题 * @author Micky */ @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(); } } }
- 开启获取连接的校验
@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); } } }