spring + ehcache 註解使用執行個體

來源:互聯網
上載者:User

標籤:

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中設定的時間     大於為緩衝正常

spring + ehcache 註解使用執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.