开发过程中经常会遇到设置redis key前缀的场景,尤其是有多条业务线,op都会给各条业务线分配特定的前缀,例如:baidu:baijiayun:xxxxx ,开发者每次拼接key的时候都要去拼接该前缀,很是麻烦,这里提供一种思路,java数据传输之前要通过,某种方式(各种序列化框架)序列化,此时可以在业务完成之后,在序列化的时候将前缀加进去
@Configuration
public class AlyRedisConfigration {
@Value("${}")
private String prefix;
@Bean
@ConfigurationProperties(prefix = "redis")
public SingleRedisConfig alyRedisConfiguration() {
return new SingleRedisConfig();
}
@Bean("alyConnectionFactory")
public LettuceConnectionFactory alyConnectionFactory(SingleRedisConfig alyRedisConfiguration) {
return ();
}
@Bean
public AlyRedisTemplate alyRedisTemplate(
@Qualifier("alyConnectionFactory") LettuceConnectionFactory alyConnectionFactory) {
AlyRedisTemplate alyRedisTemplate = new AlyRedisTemplate();
(alyConnectionFactory);
(prefixRedisSerializer());
return alyRedisTemplate;
}
private RedisSerializer<String> prefixRedisSerializer() {
return new PrefixRedisSerializer(prefix);
}
/**
* 给redis的key加上前缀,如果不需要前缀,可以通过Template的execute方法直接调用connection里的操作。
*/
static class PrefixRedisSerializer implements RedisSerializer<String> {
private final RedisSerializer<String> delegate = ();
private final String prefix;
public PrefixRedisSerializer(String prefix) {
= prefix;
}
@Override
public byte[] serialize(String s) throws SerializationException {
return (prefix + s);
}
@Override
public String deserialize(byte[] bytes) throws SerializationException {
return (bytes);
}
}
}