筆記,spring4+ehcache2配置文件


最近工作中遇到個功能需要整合ehcache,由於spring版本用的是最新的4.2.4,而在ehcache官網找到的集成配置文檔是spring3.1的,因此配了幾次都不成功,在歷經一番波折后終於成功集成了spring4.2.4+ehcache2.10.1,這里貼一下相關的配置,以作記錄。

 

maven->pom.xml

 

spring:略

ehcache:只需要引入下面這一個jar就可以了,spring4里對緩存的注解進行了加強,因此不需要引入ehcache-spring-annotations.jar

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

 

ehcache.xml:關於里面的參數說明,請參考http://www.cnblogs.com/sunxucool/p/3159076.html

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
    updateCheck="false">

    <diskStore path="java.io.tmpdir" />

    <defaultCache 
        maxElementsInMemory="10000"
        maxElementsOnDisk="0" 
        eternal="true" 
        overflowToDisk="true"
        diskPersistent="false" 
        timeToIdleSeconds="0" 
        timeToLiveSeconds="0"
        diskSpoolBufferSizeMB="50" 
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LFU" />

    <cache name="myCache"         
        maxElementsInMemory="1000"
        maxElementsOnDisk="0" 
        eternal="false" 
        overflowToDisk="false"
        diskPersistent="false" 
        timeToIdleSeconds="120" 
        timeToLiveSeconds="300"
        diskSpoolBufferSizeMB="50" 
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LFU" />

</ehcache>  

 

spring配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
        http://www.springframework.org/schema/cache  
        http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">

    <cache:annotation-driven/>

    <bean id="ehcacheManager"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:cache/ehcache.xml" />
    </bean>

    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcacheManager" />
        <property name="transactionAware" value="true" />
    </bean>

</beans>

 

java代碼使用:注意這個@Cacheable注解,和以前用過spring-ehcache的@Cacheable用法稍有區別

@Cacheable(value = "myCache", key="#condition")
public <T> T findXX(String condition) {
    // 業務代碼,ehcache會將該方法的返回結果緩存起來
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM