欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot2.x 整合redis,写缓存value序列化问题中关于RedisCacheManage

程序员文章站 2022-05-01 15:53:31
...

spring1.x里RedisCacheConfiguration中的ReidsCacheManager来进行自定义配置

springboot2.x 整合redis,写缓存value序列化问题中关于RedisCacheManage

还有springboot配置缓存过期时间,网上大部分资料是使用ReidsCacheManager来进行自定义的配置

@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager cacheManager= new RedisCacheManager(redisTemplate);
    cacheManager.setDefaultExpiration(60);
    Map<String,Long> expiresMap=new HashMap<>();
    expiresMap.put("Product",5L);
    cacheManager.setExpires(expiresMap);
    return cacheManager;
}

然而在springboot2.x中,RedisCacheManager已经变成有RedisCacheManagerBuilder的内部类

更改如下:

@Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
//                .disableCachingNullValues() // 查询id没有数据时,会报错 Cache 'emp' does not allow 'null' values.Avoid storing null via '@Cacheable(unless="#result == null")' or configure RedisCache to allow 'null' via RedisCacheConfiguration.
                .entryTtl(Duration.ofMinutes(1))  // 缓存1min过期时间
//                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer(Employee.class)));
        //关于2者区别https://blog.csdn.net/bai_bug/article/details/81222519
        redisCacheConfiguration.usePrefix();// 缓存key前缀  格式:cacheName:key 

        return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory)
                .cacheDefaults(redisCacheConfiguration).build();
//        return RedisCacheManager
//                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
//                .cacheDefaults(redisCacheConfiguration).build();
    }

其他配置可以从RedisCacheConfiguration这个类中看一下

key前缀 

public RedisCacheConfiguration computePrefixWith(CacheKeyPrefix cacheKeyPrefix) {

		Assert.notNull(cacheKeyPrefix, "Function for computing prefix must not be null!");

		return new RedisCacheConfiguration(ttl, cacheNullValues, true, cacheKeyPrefix, keySerializationPair,
				valueSerializationPair, conversionService);
	}