spring整合Ehcache

在整合以前須要作相關的準備java

  1. 在pom.xml中添加ehcache的相關依賴包。
  2. 在spring的配置文件中添加ehcache的配置。
  3. 準備一份ehcache.xml文件,配置緩存的策略。
  4. 在代碼層面上使用spring提供的註解進行具體實現。

根據以上的說明下面開始將ehcache整合到spring中。spring

  • 在pom.xml中添加依賴
<dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.9.0</version>
        </dependency>
  • 在spring.xml中配置ehcache
<bean id="ehcacheManagerBean" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache.xml"/>
        <property name="shared" value="true"/>
    </bean>

    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcacheManagerBean"/>
        <property name="transactionAware" value="true"/>
    </bean>
  • 建立ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache  updateCheck="false">
    <diskStore path="java.io.tmpdir"/>
    <defaultCache

            maxElementsInMemory="1000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            />


</ehcache>

        緩存配置數據庫

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 內存數量最大時是否清除。

 

  • 在Service層的接口實現類的方法上使用spring提供的註解實現

spring 提供的cache註解有如下幾個:緩存

@Cacheable      @CacheEvict     @CachePutspa

@Cacheable(value=」usersCache」)這個註釋的意思是,當調用這個方法的時候,會從一個名叫 usersCache的緩存中查詢,若是沒有,則執行實際的方法(即查詢數據庫),並將執行的結果存入緩存中,不然返回緩存中的對象。這裏的緩存中的 key 就是參數 userName,value 就是 Account 對象。「usersCache」緩存是在 ehcache.xml 中定義的名稱。線程

@CacheEvict 註釋來標記要清空緩存的方法,當這個方法被調用後,即會清空緩存。注意其中一個 @CacheEvict(value=」accountCache」,key=」#account.getName()」),其中的 Key 是用來指定緩存的 key 的,這裏由於咱們保存的時候用的是 account 對象的 name 字段,因此這裏還須要從參數 account 對象中獲取 name 的值來做爲 key,前面的 # 號表明這是一個 SpEL 表達式,此表達式能夠遍歷方法的參數對象,具體語法能夠參考 Spring 的相關文檔手冊。rest

@CachePut 的做用 主要針對方法配置,可以根據方法的請求參數對其結果進行緩存,和 @Cacheable 不一樣的是,它每次都會觸發真實方法的調用code

相關文章
相關標籤/搜索