spring cache 的一大缺陷是无法对集合缓存操作
例如:信箱功能
@Cacheable(value="mailCache",key="#uid+'list'")
public List<Mail> getMails(Integer uid);
@Cacheable(value = "mailCache", key = "#id")
public Mail getMail(Integer id);
@CacheEvict(value = "mailCache", key = "#mail.uid + 'list'")
@CachePut(value = "mailCache", key = "#mail.id")
public Mail update(Mail mail);
@CacheEvict(value = "mailCache", key = "#mail.uid + 'list'")
public Mail saveMail(Mail mail);
这4个接口是一个典型的数据操作接口,get、update、save、findList
其中的缓存的处理分为2部分:实体缓存(get、update、save)、集合缓存(findList)
1、执行get 方法把Mail实体缓存起来
2、执行getMail方法把Mail集合缓存起来
3、执行update更新Maill实体缓存并且清除Mail的集合缓存
4、执行save清除Mail的集合缓存
以上4点的问题所在:
1、save操作无法缓存Mail(因为缺少主键ID,Spring Cache限定了只能从参数中解析key)
2、save、update只能清除Mail的集合缓存,降低了集合缓存的利用率
为此,拓展Spring AOP Cache 添加annotation:@CacheUpdate、@CacheDelete、@CacheSave
1、在@CacheSave注解下,通过方法的返回值生成key,并且把返回值添加至集合Cache中。并且把返回值缓存起来
2、在@CahceUpdate注解下,通过参数生成key,并且把返回值更新至集合Cache中
3、在@CacheDelete注解下,通过参数生成key,并且从集合Cache中移除该实体
4、在@CacheDelete注解下,可以缓存住删除操作
以上3点做法的缺陷:
1、@CacheSave不保证顺序
2、@CacheUpdate需要自行考虑是否适用。例如:
@Cacheable(value="mailCache",key="#uid+'list'")
public List<Mail> getUnReadMails(Integer uid,boolean read){
return find("select * from Mail where uid = ? and read = ?",uid,read);
}
之前的getMail方法,参数只有uid,而uid是一个不变值。所以Mail实体update操作不会改变uid
而getUnReadMails多了一个参数read,Mail实体update是有可能update read从而影响getUnreadMails的缓存,导致不一致(这里的getUnreadMails方法就有可能多出/少一个实体,虽然@CacheUpdate有更新到最新的Mail,但是getUnreadMails的集合会多出这个)
解决办法是正确的使用@CacheDelete和@CacheUpdate
例如:上面这个例子应该在update方法上面加上一个@CacheDelete用于移除掉符合条件的实体
具体的代码因为还缺少同步、测试所以暂时不上传
分享到:
相关推荐
springboot 使用spring cache缓存 和 使用fastjson配置redis系列化,springboot 使用spring cache缓存 和 使用fastjson配置redis系列化,springboot 使用spring cache缓存 和 使用fastjson配置redis系列化,springboot ...
redis与springcache集成,对应的文章可以在我的csdn博客中找到
通过spring-cache对方法进行缓存,同时验证如何通过key更新指定的缓存!
承接上个代码将memecached调用改为交给Spring Cache代理
redis主从配置流程,关键配置项,哨兵模式实现高可用。并整合spring cache功能。快速方便
之前整合springcache+redis的时候到网上搜了很多代码方案,但是注解都不起作用,搞了很长时间,也是很郁闷。所以,把成果分享一下,避免更多人踩坑,哈哈
1、SpringCache是Spring提供的一个缓存框架,在Spring3.1版本开始支持将缓存添加到现有的spring应用程序中,在4.1开始,缓存已支持JSR-107注释和更多自定义的选项 2、Spring Cache利用了AOP,实现了基于注解的缓存...
SpringCache与redis集成,优雅的缓存解决方案.docx
简单的实现了spring cache,包括第一次存入缓存,缓存查询和缓存清空等等
spring cacke spring cacke
自己开发过程中使用到的一片Spring Cache 技术文档,很实用,
spring-cache-mongodb:基于MongoDB的Spring Cache实现
Redis-Cluster集群整合SpringCahe的一个demo,将redis作为缓存,解决分布式问题
本文是springboot 使用spring cache缓存 和 缓存数据落地到redis的研究笔记,为方便下载查看,特意分享了springboot 使用spring cache缓存 和 缓存数据落地到redis.pdf的文件。希望搭建对springboot 使用spring ...
使用Spring,SpringMVC,mybatis框架 将memcached和Spring集成,基于Spring原Cache注解
SpringCache整合Redis简单练习
spring-cache-3.5.0工具包,Java开发一般能用上,缓存工具
Spring Cache 复合缓存管理器
缓存是实际工作中非经常常使用的一种提高性能的方法, 我们会在很多场景下来...下面这篇文章主要给大家介绍了关于Spring Cache的基本使用与实现原理的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
9.spring cache