@Cacheable(value=”accountCache”), 这个注释的意思是,当调用这个方法的时候,会从一个名叫 accountCache 的缓存中查询,若是没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,不然返回缓存中的对象。这里的缓存中的 key 就是参数 userName,value 就是 Account 对象。“accountCache”缓存是在 spring*.xml 中定义的名称。html
value:缓存位置名称,不能为空,若是使用EHCache,就是ehcache.xml中声明的cache的namejava
key:缓存的key,默认为空,既表示使用方法的参数类型及参数值做为key,支持SpELspring
condition:触发条件,只有知足条件的状况才会加入缓存,默认为空,既表示所有都加入缓存,支持SpEL数据库
@Cacheable(value="accountCache",key="#userId")// 使用了一个缓存名叫 accountCache public Account getAccountByName(String userId) { // 方法内部实现不考虑缓存逻辑,直接实现业务 return getFromDB(userId); }
@Cacheable(value="accountCache",condition="#userName.length() <=4")// 缓存名叫 accountCache public Account getAccountByName(String userName) { // 方法内部实现不考虑缓存逻辑,直接实现业务 return getFromDB(userName); }
@CacheEvict 注释来标记要清空缓存的方法,当这个方法被调用后,即会清空缓存。注意其中一个 @CacheEvict(value=”accountCache”,key=”#account.getName()”),其中的 Key 是用来指定缓存的 key 的,这里由于咱们保存的时候用的是 account 对象的 name 字段,因此这里还须要从参数 account 对象中获取 name 的值来做为 key,前面的 # 号表明这是一个 SpEL 表达式,此表达式能够遍历方法的参数对象,具体语法能够参考 Spring 的相关文档手册。express
value:缓存位置名称,不能为空,同上缓存
key:缓存的key,默认为空,同上网络
condition:触发条件,只有知足条件的状况才会清除缓存,默认为空,支持SpEL 关于SpEL文档请参考:http://docs.spring.io/spring/docs/3.1.0.M1/spring-framework-reference/html/expressions.htmlspa
allEntries:true表示清除value中的所有缓存,默认为false线程
@CacheEvict(value="accountCache",key="#account.getName()")// 清空accountCache 缓存 public void updateAccount(Account account) { updateDB(account); } @CacheEvict(value="accountCache",allEntries=true)// 清空accountCache 缓存 public void reload() { reloadAll() }
@CachePut 注释,这个注释能够确保方法被执行,同时方法的返回值也被记录到缓存中,实现缓存与数据库的同步更新。code
value | 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 | 例如: @Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”} |
key | 缓存的 key,能够为空,若是指定要按照 SpEL 表达式编写,若是不指定,则缺省按照方法的全部参数进行组合 | 例如: @Cacheable(value=”testcache”,key=”#userName”) |
condition | 缓存的条件,能够为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存 | 例如: @Cacheable(value=”testcache”,condition=”#userName.len |
通常适用于更新数据,这样一来数据也被更新了,缓存中数据也被更新了
@CachePut(value="accountCache",key="#account.getName()")// 更新accountCache 缓存 public Account updateAccount(Account account) { return updateDB(account); }
CacheManager cacheManager = CacheManager.create(); // 或者 cacheManager = CacheManager.getInstance(); // 或者 cacheManager = CacheManager.create("/config/ehcache.xml"); // 或者 cacheManager = CacheManager.create("http://localhost:8080/test/ehcache.xml"); cacheManager = CacheManager.newInstance("/config/ehcache.xml"); // ....... // 获取ehcache配置文件中的一个cache Cache sample = cacheManager.getCache("sample"); // 获取页面缓存 BlockingCache cache = new BlockingCache(cacheManager.getEhcache("SimplePageCachingFilter")); // 添加数据到缓存中 Element element = new Element("key", "val"); sample.put(element); // 获取缓存中的对象,注意添加到cache中对象要序列化 实现Serializable接口 Element result = sample.get("key"); // 删除缓存 sample.remove("key"); sample.removeAll(); // 获取缓存管理器中的缓存配置名称 for (String cacheName : cacheManager.getCacheNames()) { System.out.println(cacheName); } // 获取全部的缓存对象 for (Object key : cache.getKeys()) { System.out.println(key); } // 获得缓存中的对象数 cache.getSize(); // 获得缓存对象占用内存的大小 cache.getMemoryStoreSize(); // 获得缓存读取的命中次数 cache.getStatistics().getCacheHits(); // 获得缓存读取的错失次数 cache.getStatistics().getCacheMisses();
spring-ehcache.xml配置
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache" 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"> <!-- cacheManager工厂类,指定ehcache.xml的位置 --> <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation"> <value>classpath:ehcache.xml</value> </property> </bean> <!-- 声明cacheManager --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager"> <ref local="cacheManagerFactory" /> </property> </bean> <!-- 启用缓存注解功能,这个是必须的,不然注解不会生效--> <cache:annotation-driven cache-manager="cacheManager"/> </beans>
<?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="true" monitoring="autodetect"> <diskStore path="java.io.tmpdir"/> <!-- <diskStore path="E:/cachetmpdir" /> --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="1200" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="1800" memoryStoreEvictionPolicy="LRU" /> <cache name="productCache" maxElementsInMemory="10000" eternal="false" overflowToDisk="false" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU"> </cache> </ehcache>
maxElementsInMemory :cache 中最多能够存放的元素的数量。若是放入cache中的元素超过这个数值,有两种状况:一、若overflowToDisk的属性值为true,会将cache中多出的元素放入磁盘文件中。二、若overflowToDisk的属性值为false,会根据memoryStoreEvictionPolicy的策略替换cache中原有的元素。
eternal :意思是是否永驻内存。若是值是true,cache中的元素将一直保存在内存中,不会由于时间超时而丢失,因此在这个值为true的时候,timeToIdleSeconds和timeToLiveSeconds两个属性的值就不起做用了。
timeToIdleSeconds :就是访问这个cache中元素的最大间隔时间。若是超过这个时间没有访问这个cache中的某个元素,那么这个元素将被从cache中清除。
timeToLiveSeconds : 这是cache中元素的生存时间。意思是从cache中的某个元素从建立到消亡的时间,从建立开始计时,当超过这个时间,这个元素将被从cache中清除。
overflowToDisk :溢出是否写入磁盘。系统会根据标签<diskStore path="java.io.tmpdir"/> 中path的值查找对应的属性值,若是系统的java.io.tmpdir的值是 D:/temp,写入磁盘的文件就会放在这个文件夹下。文件的名称是cache的名称,后缀名的data。如:CACHE_FUNC.data。这个属性 在解释maxElementsInMemory的时候也已经说过了。
diskExpiryThreadIntervalSeconds :磁盘缓存的清理线程运行间隔
memoryStoreEvictionPolicy :内存存储与释放策略。有三个值:
LRU -least recently used
LFU -least frequently used
FIFO-first in first out, the oldest element by creation time
diskPersistent : 是否持久化磁盘缓存。当这个属性的值为true时,系统在初始化的时候会在磁盘中查找文件名为cache名称,后缀名为index的的文件,如 CACHE_FUNC.index 。这个文件中存放了已经持久化在磁盘中的cache的index,找到后把cache加载到内存。要想把cache真正持久化到磁盘,写程序时必须注意, 在是用net.sf.ehcache.Cache的void put (Element element)方法后要使用void flush()方法。
以上时间值都是以秒做为单位的。
<diskStore>表示当内存缓存中对象数量超过类设置内存缓存数量时,将缓存对象写到硬盘,path=”java.io.tmpdir”表示把数据写到这个目录下。Java.io.tmpdir目录在运行时会根据相对路径生成。
<defaultCache>表示设定缓存的默认数据过时策略。
<cache>表示设定用具体的命名缓存的数据过时策略。
参考资料:
http://blog.springsource.com/2011/02/23/spring-3-1-m1-caching/
http://hi.baidu.com/coolcooldool/blog/item/3b541533c72b40e21a4cffda.html
部份内容来源于网络。