笔记,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会将该方法的返回结果缓存起来
}

 

posted @ 2016-01-28 10:37  Hank蝈蝈  阅读(4530)  评论(0编辑  收藏  举报