1、测试缓存
发现使用的是序列化保存对象的方式
2、缓存原理
原理:默认用的是ConcurrentMapCacheManager==ConcurrentMapCache,缓存组件来实际给缓存中存取数据 * 1).引入redis的starter,容器中保存的是RedisCacheManager * 2).RedisCacheManager帮我们创建RedisCache作为缓存组件 * 3).默认保存数据k-v都是Object,且利用序列化保存;
3、如何将缓存中的对象保存为json -- 自定义CacheManager
(1)SpringBoot 2.x 版本
@Configuration
public class MyRedisConfig {
@Bean
public RedisTemplate<Object, Object> objRedisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
template.setDefaultSerializer(serializer);
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory){
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofDays(1))
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();}
}
(2)测试