@cacheable的缓存怎么shiro 使用 cache缓存

The page is temporarily unavailable
nginx error!
The page you are looking for is temporarily unavailable.
Please try again later.
Website Administrator
Something has triggered an error on your
This is the default error page for
nginx that is distributed with
It is located
/usr/share/nginx/html/50x.html
You should customize this error page for your own
site or edit the error_page directive in
the nginx configuration file
/etc/nginx/nginx.conf.The page is temporarily unavailable
nginx error!
The page you are looking for is temporarily unavailable.
Please try again later.
Website Administrator
Something has triggered an error on your
This is the default error page for
nginx that is distributed with
It is located
/usr/share/nginx/html/50x.html
You should customize this error page for your own
site or edit the error_page directive in
the nginx configuration file
/etc/nginx/nginx.conf.The page is temporarily unavailable
nginx error!
The page you are looking for is temporarily unavailable.
Please try again later.
Website Administrator
Something has triggered an error on your
This is the default error page for
nginx that is distributed with
It is located
/usr/share/nginx/html/50x.html
You should customize this error page for your own
site or edit the error_page directive in
the nginx configuration file
/etc/nginx/nginx.conf.详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用
作者:whatlookingfor
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用,非常具有实用价值,需要的朋友可以参考下
@Cacheable
@Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
@Cacheable 作用和配置方法
缓存的名称,在 spring 配置文件中定义,必须指定至少一个
@Cacheable(value=”mycache”)
@Cacheable(value={”cache1”,”cache2”}
缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
@Cacheable(value=”testcache”,key=”#userName”)
缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存
@Cacheable(value=”testcache”,condition=”#userName.length()&2”)
@Cacheable(value=”accountCache”),这个注释的意思是,当调用这个方法的时候,会从一个名叫 accountCache 的缓存中查询,如果没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,否则返回缓存中的对象。这里的缓存中的 key 就是参数 userName,value 就是 Account 对象。“accountCache”缓存是在 spring*.xml 中定义的名称。
@Cacheable(value="accountCache")// 使用了一个缓存名叫 accountCache
public Account getAccountByName(String userName) {
// 方法内部实现不考虑缓存逻辑,直接实现业务
System.out.println("real query account."+userName);
return getFromDB(userName);
@CachePut 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用
@CachePut 作用和配置方法
缓存的名称,在 spring 配置文件中定义,必须指定至少一个
@CachePut(value=”my cache”)
缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
@CachePut(value=”testcache”,key=”#userName”)
缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存
@CachePut(value=”testcache”,condition=”#userName.length()&2”)
@CachePut 注释,这个注释可以确保方法被执行,同时方法的返回值也被记录到缓存中,实现缓存与数据库的同步更新。
@CachePut(value="accountCache",key="#account.getName()")// 更新accountCache 缓存
public Account updateAccount(Account account) {
return updateDB(account);
@CacheEvict
@CachEvict 的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空
@CacheEvict 作用和配置方法
缓存的名称,在 spring 配置文件中定义,必须指定至少一个
@CacheEvict(value=”my cache”)
缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
@CacheEvict(value=”testcache”,key=”#userName”)
缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存
@CacheEvict(value=”testcache”,condition=”#userName.length()&2”)
allEntries
是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存
@CachEvict(value=”testcache”,allEntries=true)
beforeInvocation
是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存
@CachEvict(value=”testcache”,beforeInvocation=true)
@CacheEvict(value="accountCache",key="#account.getName()")// 清空accountCache 缓存
public void updateAccount(Account account) {
updateDB(account);
@CacheEvict(value="accountCache",allEntries=true)// 清空accountCache 缓存
public void reload() {
reloadAll()
@Cacheable(value="accountCache",condition="#userName.length() &=4")// 缓存名叫 accountCache
public Account getAccountByName(String userName) {
// 方法内部实现不考虑缓存逻辑,直接实现业务
return getFromDB(userName);
@CacheConfig
所有的@Cacheable()里面都有一个value=“xxx”的属性,这显然如果方法多了,写起来也是挺累的,如果可以一次性声明完 那就省事了, 所以,有了@CacheConfig这个配置,@CacheConfig is a class-level annotation that allows to share the cache names,如果你在你的方法写别的名字,那么依然以方法的名字为准。
@CacheConfig("books")
public class BookRepositoryImpl implements BookRepository {
@Cacheable
public Book findBook(ISBN isbn) {...}
下面提供一些常用的条件缓存
//@Cacheable将在执行方法之前( #result还拿不到返回值)判断condition,如果返回true,则查缓存;
@Cacheable(value = "user", key = "#id", condition = "#id lt 10")
public User conditionFindById(final Long id)
//@CachePut将在执行完方法后(#result就能拿到返回值了)判断condition,如果返回true,则放入缓存;
@CachePut(value = "user", key = "#id", condition = "#result.username ne 'zhang'")
public User conditionSave(final User user)
//@CachePut将在执行完方法后(#result就能拿到返回值了)判断unless,如果返回false,则放入缓存;(即跟condition相反)
@CachePut(value = "user", key = "#user.id", unless = "#result.username eq 'zhang'")
public User conditionSave2(final User user)
//@CacheEvict, beforeInvocation=false表示在方法执行之后调用(#result能拿到返回值了);且判断condition,如果返回true,则移除缓存;
@CacheEvict(value = "user", key = "#user.id", beforeInvocation = false, condition = "#result.username ne 'zhang'")
public User conditionDelete(final User user)
有时候我们可能组合多个Cache注解使用;比如用户新增成功后,我们要添加id–&user;username—&user;email—&user的缓存;此时就需要@Caching组合多个注解标签了。
@Caching(put = {
@CachePut(value = "user", key = "#user.id"),
@CachePut(value = "user", key = "#user.username"),
@CachePut(value = "user", key = "#user.email")
public User save(User user) {
自定义缓存注解
比如之前的那个@Caching组合,会让方法上的注解显得整个代码比较乱,此时可以使用自定义注解把这些注解组合到一个注解中,如:
@Caching(put = {
@CachePut(value = "user", key = "#user.id"),
@CachePut(value = "user", key = "#user.username"),
@CachePut(value = "user", key = "#user.email")
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface UserSaveCache {
这样我们在方法上使用如下代码即可,整个代码显得比较干净。
@UserSaveCache
public User save(User user)
比如findByUsername时,不应该只放username–&user,应该连同id—&user和email—&user一起放入;这样下次如果按照id查找直接从缓存中就命中了
cacheable = {
@Cacheable(value = "user", key = "#username")
@CachePut(value = "user", key = "#result.id", condition = "#result != null"),
@CachePut(value = "user", key = "#result.email", condition = "#result != null")
public User findByUsername(final String username) {
System.out.println("cache miss, invoke find by username, username:" + username);
for (User user : users) {
if (user.getUsername().equals(username)) {
其实对于:id—&user;username—-&user;email—&user;更好的方式可能是:id—&user;username—&id;email—&id;保证user只存一份;如:
@CachePut(value="cacheName", key="#user.username", cacheValue="#user.username")
public void save(User user)
@Cacheable(value="cacheName", key="#user.username", cacheValue="#caches[0].get(#caches[0].get(#username).get())")
public User findByUsername(String username)
SpEL上下文数据
Spring Cache提供了一些供我们使用的SpEL上下文数据,下表直接摘自Spring官方文档:
methodName
当前被调用的方法名
root.methodName
当前被调用的方法
root.method.name
当前被调用的目标对象
root.target
targetClass
当前被调用的目标对象类
root.targetClass
当前被调用的方法的参数列表
root.args[0]
当前方法调用使用的缓存列表(如@Cacheable(value={“cache1”, “cache2”})),则有两个cache
root.caches[0].name
argument name
执行上下文
当前被调用的方法的参数,如findById(Long id),我们可以通过#id拿到参数
执行上下文
方法执行后的返回值(仅当方法执行之后的判断有效,如‘unless','cache evict'的beforeInvocation=false)
@CacheEvict(value = "user", key = "#user.id", condition = "#root.target.canCache() and #root.caches[0].get(#user.id).get().username ne #user.username", beforeInvocation = true)
public void conditionUpdate(User user)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具Spring 缓存注解@Cacheable的用法 - CSDN博客
Spring 缓存注解@Cacheable的用法
&&&&&&& 在Spring中通过获取MemCachedClient来实现与memcached服务器进行数据读取的方式。不过,在实际开发中,我们往往是通过Spring的@Cacheable来实现数据的缓存的,所以,本文给大家详细介绍一下@Cacheable的用法。首先,在使用@Cacheable之前,我们要做好准备工作。
第一步:要导入相应的jar包。
&& &classpathentry kind=&lib& path=&lib/spring-core-4.1.4.RELEASE.jar&/&
&& &&classpathentry kind=&lib& path=&lib/spring-cache-1.0.10.jar&/&
&& &&classpathentry kind=&lib& path=&lib/spring-context-4.1.4.RELEASE.jar&/&
&& &&classpathentry kind=&lib& path=&lib/spring-beans-4.1.4.RELEASE.jar&/&
&& &&classpathentry kind=&lib& path=&lib/commons-logging-1.2.jar&/&
&& &&classpathentry kind=&lib& path=&lib/log4j-1.2.17.jar&/&
&& &&classpathentry kind=&lib& path=&lib/spring-expression-4.1.4.RELEASE.jar&/&
&& &&classpathentry kind=&lib& path=&lib/java_memcached-release_2.0.1.jar&/&
&& &&classpathentry kind=&lib& path=&lib/spring-aop-4.1.4.RELEASE.jar&/&
&& &&classpathentry kind=&lib& path=&lib/spring-aspects-4.1.4.RELEASE.jar&/&
&& &&classpathentry kind=&lib& path=&lib/spring-context-support-4.1.4.RELEASE.jar&/&
&& &&classpathentry kind=&lib& path=&lib/spring-tx-4.1.4.RELEASE.jar&/&
&& &&classpathentry kind=&lib& path=&lib/aopalliance-1.0.jar&/&
&& &&classpathentry kind=&lib& path=&lib/ognl-3.0.6.jar&/&
&& &&classpathentry kind=&lib& path=&lib/trafficCounter-1.0.2.jar&/&
&& &&classpathentry kind=&lib& path=&lib/aspectjweaver-1.8.4.jar&/&
&& &&classpathentry kind=&lib& path=&lib/javassist-3.11.0.GA.jar&/&
第二步:xml文件中增加命名空间。
&span style=&font-size:14&&&?xml version=&1.0& encoding=&UTF-8&?&
&beans xmlns=&http://www.springframework.org/schema/beans&
xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance&
xmlns:cache=&http://www.springframework.org/schema/cache&
xmlns:context=&http://www.springframework.org/schema/context&
xsi:schemaLocation=&http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd&&&/span&
之后添加如下声明:
&/pre&&pre name=&code& class=&html&&&span style=&font-size:14&&&?xml version=&1.0& encoding=&UTF-8&?&
&beans xmlns=&http://www.springframework.org/schema/beans&
xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance&
xmlns:cache=&http://www.springframework.org/schema/cache&
xmlns:context=&http://www.springframework.org/schema/context&
xsi:schemaLocation=&http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd&&
&!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 --&
&cache:annotation-driven cache-manager=&cacheManager& /&
&!-- cacheManager工厂类,指定ehcache.xml的位置 --&
&bean id=&cacheManagerFactory& class=&org.springframework.cache.ehcache.EhCacheManagerFactoryBean&&
&property name=&configLocation&
value=&classpath:cache/ehcache.xml&/&
&!-- 声明cacheManager --&
&bean id=&cacheManager& class=&org.springframework.cache.ehcache.EhCacheCacheManager&&
&property name=&cacheManager& ref=&cacheManagerFactory&/&
&/beans&&/span&第二步:&ehcache.xml
&span style=&font-size:14&&&?xml version=&1.0& encoding=&UTF-8&?&
&ehcache xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance&
xsi:noNamespaceSchemaLocation=&http://ehcache.org/ehcache.xsd&
updateCheck=&false& dynamicConfig=&false& monitoring=&autodetect&&
&diskStore path=&java.io.tmpdir& /&
diskStore path:用来配置磁盘缓存使用的物理路径
name: 缓存名称,cache的唯一标识(ehcache会把这个cache放到HashMap里)
eternal=&false&
元素是否永恒,如果是就永不过期(必须设置)
maxElementsOnDisk====磁盘缓存中最多可以存放的元素数量,0表示无穷大
maxElementsInMemory=&1000& 内存缓存中最多可以存放的元素数量(必须设置)
timeToIdleSeconds=&0&
导致元素过期的访问间隔(秒为单位). 0表示可以永远空闲,默认为0
timeToLiveSeconds=&600& 元素在缓存里存在的时间(秒为单位). 0 表示永远存在不过期
overflowToDisk=&false&
当缓存达到maxElementsInMemory值是,是否允许溢出到磁盘(必须设置)
diskPersistent=&false&
磁盘缓存在VM重新启动时是否保持(默认为false)
diskExpiryThreadIntervalSeconds=&100& 磁盘失效线程运行时间间隔,默认是120秒
memoryStoreEvictionPolicy=&LFU& 内存存储与释放策略.当达到maxElementsInMemory时
共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)默认使用&最近使用&策略
&defaultCache
eternal=&false&
maxElementsInMemory=&3000&
timeToIdleSeconds=&3600&
timeToLiveSeconds=&0&
overflowToDisk=&true&
diskPersistent=&false&
diskExpiryThreadIntervalSeconds=&100&
memoryStoreEvictionPolicy=&LRU&/&
&cache name=&propConfigCache&
eternal=&false&
maxElementsInMemory=&3000&
overflowToDisk=&true&
timeToIdleSeconds=&0&
timeToLiveSeconds=&1440&
memoryStoreEvictionPolicy=&LFU&/&
&cache name=&workTimeCache&
eternal=&false&
maxElementsInMemory=&3000&
overflowToDisk=&true&
timeToIdleSeconds=&0&
timeToLiveSeconds=&1440&
memoryStoreEvictionPolicy=&LFU&/&
&cache name=&threeInOneCache&
eternal=&false&
maxElementsInMemory=&3000&
overflowToDisk=&true&
timeToIdleSeconds=&0&
timeToLiveSeconds=&1440&
memoryStoreEvictionPolicy=&LFU&/&
&cache name=&transferCache&
eternal=&false&
maxElementsInMemory=&1000&
overflowToDisk=&true&
timeToIdleSeconds=&0&
timeToLiveSeconds=&1440&
memoryStoreEvictionPolicy=&LFU&/&
&cache name=&threeInOneFavCache&
eternal=&false&
maxElementsInMemory=&3000&
overflowToDisk=&true&
timeToIdleSeconds=&0&
timeToLiveSeconds=&1440&
memoryStoreEvictionPolicy=&LFU&/&
&cache name=&reserveTimeCache&
eternal=&false&
maxElementsInMemory=&3000&
overflowToDisk=&true&
timeToIdleSeconds=&0&
timeToLiveSeconds=&1440&
memoryStoreEvictionPolicy=&LFU&/&
&cache name=&mqServerNameCache&
eternal=&false&
maxElementsInMemory=&3000&
overflowToDisk=&true&
timeToIdleSeconds=&0&
timeToLiveSeconds=&1440&
memoryStoreEvictionPolicy=&LFU&/&
&cache name=&schWorkTimeCache&
eternal=&false&
maxElementsInMemory=&3000&
overflowToDisk=&true&
timeToIdleSeconds=&0&
timeToLiveSeconds=&1440&
memoryStoreEvictionPolicy=&LFU&/&
&/ehcache&&/span&
@Cacheable&支持如下几个参数:
value:缓存位置名称,不能为空,如果使用EHCache,就是ehcache.xml中声明的cache的name
key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,支持SpEL
condition:触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL
&span style=&font-size:14&&//将缓存保存进andCache,并使用参数中的userId加上一个字符串(这里使用方法名称)作为缓存的key
@Cacheable(value=&andCache&,key=&#userId + 'findById'&)
public SystemUser findById(String userId) {
SystemUser user = (SystemUser) dao.findById(SystemUser.class, userId);
//将缓存保存进andCache,并当参数userId的长度小于32时才保存进缓存,默认使用参数值及类型作为缓存的key
@Cacheable(value=&andCache&,condition=&#userId.length & 32&)
public boolean isReserved(String userId) {
System.out.println(&hello andCache&+userId);
@CacheEvict&支持如下几个参数:
value:缓存位置名称,不能为空,同上
key:缓存的key,默认为空,同上
condition:触发条件,只有满足条件的情况才会清除缓存,默认为空,支持SpEL
allEntries:true表示清除value中的全部缓存,默认为false
&span style=&font-size:14&&
//清除掉指定key的缓存
@CacheEvict(value=&andCache&,key=&#user.userId + 'findById'&)
public void modifyUserRole(SystemUser user) {
System.out.println(&hello andCache delete&+user.getUserId());
//清除掉全部缓存
@CacheEvict(value=&andCache&,allEntries=true)
public final void setReservedUsers(String[] reservedUsers) {
System.out.println(&hello andCache deleteall&);
一般来说,我们的更新操作只需要刷新缓存中某一个值,所以定义缓存的key值的方式就很重要,最好是能够唯一,因为这样可以准确的清除掉特定的缓存,而不会影响到其它缓存值&,
比如我这里针对用户的操作,使用(userId+方法名称)的方式设定key值&,当然,你也可以找到更适合自己的方式去设定。
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。
Ehcache最初是由Greg Luck于2003年开始开发。2009年,该项目被Terracotta购买。软件仍然是开源,但一些新的主要功能(例如,快速可重启性之间的一致性的)只能在商业产品中使用,例如Enterprise EHCache and BigMemory。,维基媒体Foundationannounced目前使用的就是Ehcache技术。
主要的特性有:
3. 多种缓存策略
4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题
5. 缓存数据会在重启的过程中写入磁盘
6. 可以通过RMI、可插入API等方式进行分布式缓存
7. 具有缓存和缓存管理器的侦听接口
8. 支持多管理器实例,以及一个实例的多个缓存区域
9. 提供Hibernate的缓存实现
本文已收录于以下专栏:
相关文章推荐
@Cacheable、@CachePut、@CacheEvict 注释介绍
表 1. @Cacheable 作用和配置方法
@Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其...
程序员越来越值钱了
今年是程序员的招聘大年,企业给出的offer平均比去年要多出30%到50%。如果不对老员工进行大幅度地加薪,将会出现大面积的严重倒挂现象,虽然出现这种自毁长城的可能性很小。
Spring缓存注解的介绍以及常用总结
大话西游2老朋友序列号大话西游2老朋友序列号有效玩家定义:  1.网易通行证帐号曾在《大话西游2》中产生过消费;  2.网易通行证帐号30天以内登陆《大话西游2》时间不足2小时,例如您发展的玩家在5月...
在spring中通过获取MemCachedClient来实现与memcached服务器进行数据读取的方式。不过,在实际开发中,我们往往是通过Spring的@Cacheable来实现数据的缓存的,所以,...
maven项目中在pom.xml中依赖2个jar包:
redis.clients
org.springframewor...
@Transactional spring 事务注解
默认遇到throw new RuntimeException(&...&);会回滚
需要捕获的throw new Exception(&......
转自:http://tom-/blog/2104430
缓存注解有以下三个:
@Cacheable      @CacheEvict     @CachePut...
他的最新文章
讲师:宋宝华
讲师:何宇健
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)

我要回帖

更多关于 cacheable 更新缓存 的文章

 

随机推荐