一 背景
由于redis一般都是多个服务共用,但是由于之前的一些服务缓存key都未指定前缀,导致查看redis缓存的时候非常混乱,也不知道对应的缓存是哪个服务写入的。
另外,由于写缓存的地方较多并且未统一维护缓存key,一个个去改可能会改漏,那么怎么可以做到把写缓存的地方统一给缓存key添加上前缀呢。
如果你们服务设计比较合理,缓存key都统一放在一个常量类中维护,添加前缀非常方便,那么也就不需要往下看了。
二 统一添加缓存key
自定义一个KeyStringRedisSerializer1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24public class KeyStringRedisSerializer implements RedisSerializer<String> {
private final String CACHE_PREFIX = "test-server:";
...
/*
* (non-Javadoc)
* @see org.springframework.data.redis.serializer.RedisSerializer#deserialize(byte[])
*/
public String deserialize(@Nullable byte[] bytes) {
return (bytes == null ? null : new String(bytes, charset).replaceFirst(CACHE_PREFIX, ""));
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.serializer.RedisSerializer#serialize(java.lang.Object)
*/
public byte[] serialize( String string) {
return (string == null ? null : (CACHE_PREFIX + string).getBytes(charset));
}
}
配置中指定KeySerializer为该自定义的Serializer1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(redisConnectionFactory);
RedisSerializer<String> keySerializer = new KeyStringRedisSerializer();
stringRedisTemplate.setKeySerializer(keySerializer);
return stringRedisTemplate;
}
public RedisTemplate<String, Object> objectRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisSerializer<String> serializer = new StringRedisSerializer();
RedisSerializer<String> keySerializer = new KeyStringRedisSerializer();
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(keySerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(serializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
到此为止,就已经为该服务统一添加了缓存前缀 test-server: