RedisNamespaceSerializer

  1. import java.nio.charset.Charset;
  2. import java.nio.charset.StandardCharsets;
  3. import org.springframework.data.redis.serializer.StringRedisSerializer;
  4. public class RedisNamespaceSerializer extends StringRedisSerializer {
  5. private String namespace;
  6. private Charset charset;
  7. public RedisNamespaceSerializer(String namespace) {
  8. this(namespace, StandardCharsets.UTF_8);
  9. }
  10. public RedisNamespaceSerializer(String namespace, Charset charset) {
  11. this.namespace = namespace;
  12. this.charset = charset;
  13. }
  14. public String deserialize(byte[] bytes) {
  15. String key = new String(bytes, this.charset);
  16. int index = key.indexOf(this.namespace);
  17. if (index == 0) {
  18. key = key.substring(this.namespace.length() + 1);
  19. }
  20. return key;
  21. }
  22. public byte[] serialize(String string) {
  23. if (string == null) {
  24. return null;
  25. } else {
  26. String key = this.namespace + "." + string;
  27. return key.getBytes(this.charset);
  28. }
  29. }
  30. }

SpringBootConfig

  1. @Configuration
  2. public class RedisConfig {
  3. @Value("${spring.redis.namespace:'DEFAULT'}")
  4. private String namespace;
  5. @Bean
  6. public RedisTemplate<String, Object> objRedisTemplate(RedisConnectionFactory factory) {
  7. RedisTemplate<String, Object> template = new RedisTemplate<>();
  8. template.setKeySerializer(new RedisNamespaceSerializer(namespace));
  9. template.setValueSerializer(new JdkSerializationRedisSerializer());
  10. template.setHashKeySerializer(new StringRedisSerializer());
  11. template.setHashValueSerializer(new JdkSerializationRedisSerializer());
  12. template.setConnectionFactory(factory);
  13. return template;
  14. }
  15. @Bean
  16. public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
  17. StringRedisTemplate template = new StringRedisTemplate();
  18. template.setKeySerializer(new RedisNamespaceSerializer(namespace));
  19. template.setConnectionFactory(factory);
  20. return template;
  21. }
  22. }

Yml Config

  1. redis:
  2. host: xxx
  3. port: xxx
  4. namespace: xxx.dev