您的位置:首页 > 编程语言 > Java开发

spring EhCache缓存之annotation注解

2017-05-26 16:25 267 查看
转: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

<?xml version="1.0" encoding="UTF-8"?>  
<ehcache updateCheck="false">  
    <diskStore path="java.io.tmpdir"/>  
<!--  
       name:缓存名称。  
       maxElementsInMemory:缓存最大个数。  
       eternal:对象是否永久有效,一但设置了,timeout将不起作用。  
       timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。  
                仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。  
       timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。  
                    仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。  
       overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。  
       diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。  
       maxElementsOnDisk:硬盘最大缓存个数。  
       diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts   
                of the Virtual Machine. The default value is false.  
       diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。  
       memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。  
                        默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。  
       clearOnFlush:内存数量最大时是否清除。  
    -->  
    <defaultCache  
            maxElementsInMemory="10000"  
            eternal="false"  
            timeToIdleSeconds="60"  
            timeToLiveSeconds="60"  
            overflowToDisk="true"  
            maxElementsOnDisk="10000000"  
            diskPersistent="false"  
            diskExpiryThreadIntervalSeconds="120"  
            memoryStoreEvictionPolicy="LRU"  
            />  
  
   <cache name="QY_api_productTop" maxElementsInMemory="10000" eternal="false"  
           timeToIdleSeconds="20" timeToLiveSeconds="20" overflowToDisk="false"  
           diskPersistent="false" diskExpiryThreadIntervalSeconds="1"/>  
</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/ href="http://lib.csdn.net/base/javaee" target=_blank>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)

  [b]key="#isbn.id"  对象缓存的key值,需要保证唯一,[/b]用的是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.   清除[b]QY_api_productTop[/b]缓存中所有对象

@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中设置的时间     大于为缓存正常
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: