使用spring-data-redis2.x版本时,将@Cacheable缓存key值时默认会给value或cacheNames后加上双冒号 改为 单冒号
默认双冒号:
修改配置:
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
/**
* 缓存配置管理器
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
// 以锁写入的方式创建RedisCacheWriter对象
RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory);
// 设置CacheManager的Value序列化方式
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = jackson2JsonRedis();
RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer);
// 创建默认缓存配置对象、 将@Cacheable缓存key值时默认会给value或cacheNames后加上双冒号 改为 单冒号
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair).computePrefixWith(name -> name + ":");
RedisCacheManager cacheManager = new RedisCacheManager(writer, config);
return cacheManager;
}
// 其他配置...
}
或者:
@Configuration
public class SpringCacheConfig{
@Bean
public CacheManager cacheManager(LettuceConnectionFactory lettuceConnectionFactory){
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHour(1)
//变双冒号为单冒号
.computePrefixWith(name -> name +":")
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.RedisCacheManagerBuilder
.fromConnectionFactory(lettuceConnectionFactory)
.cacheDefaults(config)
.transactionAware()
.build();
return cacheManager;
}
...其他配置
}