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

SpringBoot中1.0、2.0中自定义缓存的区别

程序员文章站 2022-04-30 17:17:48
...

SpringBoot1.0中

//自定义缓存文本
@Bean
public RedisTemplate<Object, Employee> empredisTemplate(RedisConnectionFactory redisConnectionFactory) {
	RedisTemplate<Object, Employee> template = new RedisTemplate<>();
	template.setConnectionFactory(redisConnectionFactory);
	Jackson2JsonRedisSerializer<Employee> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Employee.class);
	template.setDefaultSerializer(jackson2JsonRedisSerializer);
	return template;
}
//自定义CacheManager
@Bean
public RedisCacheManager empCacheManager(RedisTemplate<Object,Employee> empRedisTemplate){
	RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
	cacheManager.setUsePrefix(true);
	
	return cacheManager;
}

SpringBoot2.0中

@Bean
public RedisCacheManager employeeCacheManager(RedisConnectionFactory redisConnectionFactory){
    RedisSerializer<String> redisSerializer = new StringRedisSerializer();
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

    //解决查询缓存转换异常的问题
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    jackson2JsonRedisSerializer.setObjectMapper(om);

    // 配置序列化(解决乱码的问题)
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
            .disableCachingNullValues();

    return  RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config).build();
}

区别:
通过代码可以看到主要区别就是RedisCacheManager的创建流程

相关标签: java