RedisNamespaceSerializer
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.springframework.data.redis.serializer.StringRedisSerializer;
public class RedisNamespaceSerializer extends StringRedisSerializer {
private String namespace;
private Charset charset;
public RedisNamespaceSerializer(String namespace) {
this(namespace, StandardCharsets.UTF_8);
}
public RedisNamespaceSerializer(String namespace, Charset charset) {
this.namespace = namespace;
this.charset = charset;
}
public String deserialize(byte[] bytes) {
String key = new String(bytes, this.charset);
int index = key.indexOf(this.namespace);
if (index == 0) {
key = key.substring(this.namespace.length() + 1);
}
return key;
}
public byte[] serialize(String string) {
if (string == null) {
return null;
} else {
String key = this.namespace + "." + string;
return key.getBytes(this.charset);
}
}
}
SpringBootConfig
@Configuration
public class RedisConfig {
@Value("${spring.redis.namespace:'DEFAULT'}")
private String namespace;
@Bean
public RedisTemplate<String, Object> objRedisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setKeySerializer(new RedisNamespaceSerializer(namespace));
template.setValueSerializer(new JdkSerializationRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new JdkSerializationRedisSerializer());
template.setConnectionFactory(factory);
return template;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setKeySerializer(new RedisNamespaceSerializer(namespace));
template.setConnectionFactory(factory);
return template;
}
}
Yml Config
redis:
host: xxx
port: xxx
namespace: xxx.dev