spring EhCache缓存之annotation注解

来源:互联网 发布:2008 如何开放端口 编辑:程序博客网 时间:2024/05/14 12:03

转:http://blog.csdn.net/lemonzone2010/article/details/45199135

1.pom.xml中添加ehcache依赖包

        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.9.1</version>
        </dependency>

2.在classpath下增加ehcache配置文件 ehcache.xml

[xml] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ehcache updateCheck="false">  
  3.     <diskStore path="java.io.tmpdir"/>  
  4. <!--  
  5.        name:缓存名称。  
  6.        maxElementsInMemory:缓存最大个数。  
  7.        eternal:对象是否永久有效,一但设置了,timeout将不起作用。  
  8.        timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。  
  9.                 仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。  
  10.        timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。  
  11.                     仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。  
  12.        overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。  
  13.        diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。  
  14.        maxElementsOnDisk:硬盘最大缓存个数。  
  15.        diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts   
  16.                 of the Virtual Machine. The default value is false.  
  17.        diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。  
  18.        memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。  
  19.                         默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。  
  20.        clearOnFlush:内存数量最大时是否清除。  
  21.     -->  
  22.     <defaultCache  
  23.             maxElementsInMemory="10000"  
  24.             eternal="false"  
  25.             timeToIdleSeconds="60"  
  26.             timeToLiveSeconds="60"  
  27.             overflowToDisk="true"  
  28.             maxElementsOnDisk="10000000"  
  29.             diskPersistent="false"  
  30.             diskExpiryThreadIntervalSeconds="120"  
  31.             memoryStoreEvictionPolicy="LRU"  
  32.             />  
  33.   
  34.    <cache name="QY_api_productTop" maxElementsInMemory="10000" eternal="false"  
  35.            timeToIdleSeconds="20" timeToLiveSeconds="20" overflowToDisk="false"  
  36.            diskPersistent="false" diskExpiryThreadIntervalSeconds="1"/>  
  37. </ehcache>  




3.spring配置文件 applicationContext.xml 需要注意添加红色斜体部分配置

<beans
 xmlns:cache="http://www.springframework.org/schema/cache"
 xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd"
 >

<!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->
<cache:annotation-driven cache-manager="ehcacheManager"/>
<!-- cacheManager工厂类,指定ehcache.xml的位置 -->
<bean id="ehcacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml" />
</bean>
<!-- 声明cacheManager -->
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcacheManagerFactory" />
</bean>


4.在service层增加注解配置

4.1 Using Spring 3.1      spring 3.1 及以上版本配置

@Cacheable

Cache a method call. In the following example, the value is the return type, a Manual. The key is extracted from the ISBN argument using the id.

@org.springframework.cache.annotation.Cacheable(value="QY_api_productTop", key="#isbn.id") public Manual findManual(ISBN isbn, boolean checkWarehouse)

  key="#isbn.id"  对象缓存的key值,需要保证唯一,用的是Spring的 SpEL表达式, 取值为 isbn对象的id属性值

  value="QY_api_productTop":指的是ehcache.xml里的缓存名字

还支持条件condition,包括 属性 id<10,如下:

@Cacheable(value = "QY_api_productTop",key="#isbn.id",condition = "#isbn.id<10")public Manual findManual(ISBN isbn, boolean checkWarehouse)

  

@CacheEvict 

Clears the cache when called.   清除QY_api_productTop缓存中所有对象

@org.springframework.cache.annotation.CacheEvict(value = "QY_api_productTop", allEntries=true) public void loadManuals(Long id)


可以清除指定对象的缓存例如:

@CacheEvict(value = "QY_api_productTop", key = "#id")public void loadManuals(Long id)


4.2 Spring 2.5 to 3.1  版本配置   还依赖以下jar

<dependency>  

    <groupId>com.googlecode.ehcache-spring-annotations</groupId>  

    <artifactId>ehcache-spring-annotations</artifactId>  

    <version>1.1.2</version>  

    <type>jar</type>  

    <scope>compile</scope>  

</dependency> 

This open source, led by Eric Dalquist, predates the Spring 3.1 project. You can use it with earlier versions of Spring, or you can use it with 3.1.

@Cacheable

As with Spring 3.1 it uses an @Cacheable annotation to cache a method. In this example calls to findMessage are stored in a cache named “messageCache”. The values are of type Message. The id for each entry is the id argument given.

@Cacheable(cacheName = "messageCache")
public Message findMessage(long id)

@TriggersRemove

And for cache invalidation, there is the @TriggersRemove annotation. In this example, cache.removeAll() is called after the method is invoked.

@TriggersRemove(cacheName = "messagesCache",
when = When.AFTER_METHOD_INVOCATION, removeAll = true)
public void addMessage(Message message)


5.测试验证, 查看打印出来的sql

例如hibernate配置中设置show_sql=true

<prop key="hibernate.show_sql">true</prop>

 5.1 第一次访问缓存方法后在缓存时间内多次访问查看是否有sql输出  ,  没有为缓存正常

 5.2 第二次输出时间和第一次时间间隔是不是大于 ehcache.xml中设置的时间     大于为缓存正常


原创粉丝点击