springboot 集成redis key乱码\xac\xed\x00\x05t\x00\x0eHAOKE_HOT_WORD

文章目录

      • 场景
      • 分析
      • 解决

场景

  • springboot集成redis集群 检查key时发现key是二进制格式的 \xac\xed\x00\x05t\x00\x0eHAOKE_HOT_WORD

分析

RedisTemplate模板类在操作redis时默认使用JdkSerializationRedisSerializer来进行序列化

解决

  1. 序列化方式切换成StringRedisSerializer
  2. 通过配置bean的方式配置
## RedisClusterConfig.java
@Configuration
public class RedisClusterConfig {
    @Autowired
    private ClusterConfigurationProperties clusterConfigurationProperties;

    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration(clusterConfigurationProperties.getNodes());
        clusterConfiguration.setMaxRedirects(clusterConfigurationProperties.getMaxRedirects());
        return new JedisConnectionFactory(clusterConfiguration);
    }

    @Bean
    public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }
}

### ClusterConfigurationProperties.java
@Configuration
@ConfigurationProperties(prefix = "spring.redis.cluster")
@Data
public class ClusterConfigurationProperties {
    private List<String> nodes;

    private Integer maxRedirects;
}


你可能感兴趣的:(java,redis,redis,java,spring,boot)