spring cache问题记录

1.是否可以设置过期时间 timeout ttl

对于单个key设置过期时间 需要自定义CacheManager, 见3中的问题
spring boot 1版本可以重写RedisCacheManager#computeExpiration
spring boot 2版本方案 :[参考]https://cloud.tencent.com/developer/article/1497599

2. @Cacheable不生效?

返回null, 没有保存到redis, 再次查询时以为没走AOP aspect
(见3中的问题)
另外一种是方法内部调用,不会走aop

3. 是否可以保存null value

redis是不支持保存Null的, 但是spring-cache可以把null设置成byte 0, 反序列化时再判断如果为0就setnull

需要设置RedisCacheManager cacheNullValues = true, 见构造方法, 默认cacheNullValues =null是不支持保存null value的

null value的序列化工具也不能使用下图中的一个,可以使用GenericJackson2JsonRedisSerializer或者fastjson实现

StringRedisSerializer默认实现只能序列化String, 会有很多的classCastException (还不容易定位到底是哪出错了), 最好也自己实现
ExtStringRedisSerializer implements RedisSerializer<Object>

4. cacheable解释

cachenames生成key的前缀, key指定具体的缓存id(可以使用springEL表达式获取查询参数的field)

redis中的示例 : 中间有个冒号

多字段时 key写法

condition与unless

condition是在进入方法前运行 SpEL表达式, 决定是否需要从cache中读
unless 是在方法后运行 决定是否写到cache中

一个示例:
@Cacheable(cacheNames="xxx#200", key="#p0", condition="#p0?.size()<1000", unless="#result?")
参数list的大小不超过100, 并且结果不为空时

5. mybatis mapper接口上使用cacheable找不到参数??

https://blog.csdn.net/f641385712/article/details/95169002
解决方法:
1.使用#a0 #p0的方式, 是从0开始的,cacheable javadoc示例写的是p1,误导人
2.开启Java8的-parameters 编译参数

posted @ 2019-10-11 21:30  funny_coding  阅读(623)  评论(0编辑  收藏  举报
build beautiful things, share happiness