使用Lettuce客户端或者redis连接变化时的触发事件

文章目录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

@Configuration
@EnableCaching
public class CacheConfig {

@Bean
public RedisConnectionFactory redisConnectionFactory() {

RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
config.setHostName("127.0.0.1");
config.setPort(11);
config.setPassword("root");

return new LettuceConnectionFactory(config);
}

@Primary
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();

template.setConnectionFactory(factory);

StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializer);

template.setHashKeySerializer(stringRedisSerializer);

GenericJackson2JsonRedisSerializer redisSerializer = new GenericJackson2JsonRedisSerializer();
template.setValueSerializer(redisSerializer);

template.setHashValueSerializer(redisSerializer);
return template;

}

@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {

RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer())).disableCachingNullValues();

return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(cacheConfiguration).build();
}
}

同时实现 RedisConnectionStateListener 保证在onRedisConnected,onRedisDisconnected,onRedisExceptionCaught下运行时的调用注意下列触发事件需要在RedisClient 下注册进去,保证后续的调用成功

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class CustomRedisConnectionStateListener implements RedisConnectionStateListener {

@Override
public void onRedisConnected(RedisConnection connection) {
// 处理连接成功的逻辑
}

@Override
public void onRedisDisconnected(RedisConnection connection) {
// 处理连接断开的逻辑
}

@Override
public void onRedisExceptionCaught(RedisConnection connection, Throwable exception) {
// 处理连接异常的逻辑
}
}