m0_37282062
暮歌半生情朽
2019-01-05 16:33

SpringBoot2.1.1整合redis出现的

  • spring
  • java
  • maven
  • intellij-idea
  • java-ee

问题描述:

环境:SpringBoot2.1.1

保存在redis中的键值有问题:
注解
@Cacheable(cacheNames = {"user"}, key = "'id:'+#userId")
保存在redis中的键值应该为:**user:id:1**,但实际却是:**user::id:1**,user和id之间多了一个冒号,如果使用redisTemplate就不会出现这种问题。跟踪了很久的代码也没有解决这个问题,基本配置和网上的没有什么两样,甚至是直接拷贝网上的配置代码,也是如此,有人遇到这个问题吗?个人感觉是SpringBoot2.1.1的Bug,不知道其他有人有吗?

// 配置文件
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(30))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
                .disableCachingNullValues();

        RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .build();

        return redisCacheManager;
    }

    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        redisTemplate.setKeySerializer(keySerializer());
        redisTemplate.setHashKeySerializer(keySerializer());
        redisTemplate.setValueSerializer(valueSerializer());
        redisTemplate.setHashValueSerializer(valueSerializer());

        return redisTemplate;
    }


    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }

    private RedisSerializer<Object> valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答