环境
MacBook Pro
Intellij IDEA
前言
在使用注解@Cacheable
时,不能设置缓存时间,使用起来不是很爽,
稍微研究了一下;
配置
文件路径:
因为其不支持设置缓存时间,所以得通过RedisCacheManager
的方式来设置
/**
* @author yutao
* @since 2020/3/31 7:03 下午
*/
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
public class RedisCacheConfig {
/**
* @param redisProperties 可以通过Apollo设置spring.redis.timeout
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisCacheManager setupRedisCacheManager(RedisProperties redisProperties,
RedisConnectionFactory redisConnectionFactory) {
ObjectMapper mapper = new ObjectMapper();
// 序列化时允许非常量字段均输出类型
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
// 支持解析Joda Time
mapper.registerModule(new JodaModule());
// 支持解析时间里面带T的格式
mapper.registerModule(new JavaTimeModule());
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
// 设置超时时间
.entryTtl(Optional.ofNullable(redisProperties.getTimeout()).orElse(Duration.ofMinutes(1L)))
// 设置key的序列化器
.serializeKeysWith(fromSerializer(new StringRedisSerializer()))
// 设置value的序列化器
.serializeValuesWith(fromSerializer(new GenericJackson2JsonRedisSerializer(mapper)))
// 禁止缓存null值
.disableCachingNullValues();
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(redisCacheConfiguration).transactionAware().build();
}
}
joda time 的 toString 并不简单,比如LocalDate类型的 “2014-05-05” 转化到 json 后会有很长一串数据,再从 json 转到 joda time,jackson 报错,序列化有问题了。
在 jackson 2.0 (也就是 fastxml)以后,处理 joda time 有一种很简单的做法,就是直接注册 joda time module 到 jackson mapper
注意:
String string="{\"date\":1571887801613,\"aa\":{},\"amount1\":1.1,\"uname\":\"Tom\"}";
对上面的字符串进行反序列化,但是因为date:1571887801613
,不能明确知道其类型,所以反序列化失败。
所以我们需要ObjectMapper.DefaultTyping.NON_FINAL
配置。
ObjectMapper.DefaultTyping.NON_FINAL
配置,会在序列化时记录对象类型,以便反序列化时得到对应的具体对象。
依赖
springBootPluginVersion = '2.1.5.RELEASE'
// cache support
compile("org.springframework.boot:spring-boot-starter-cache:$springBootPluginVersion")
compile("org.springframework.boot:spring-boot-starter-data-redis:$springBootPluginVersion")
参考地址:
https://www.jianshu.com/p/c5fcd2a1ab49