spring EhCache緩存之annotation註解

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 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/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中設置的時間     大於爲緩存正常


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章