applicationContext.xml
<!-- Cache配置 -->
<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:shared="true"
p:configLocation="classpath:ehcache.xml"/>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="ehCacheManagerFactory"/>
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="txswx-ehcache">
<diskStore path="java.io.tmpdir"/>
<!-- DefaultCache setting. -->
<defaultCache maxEntriesLocalHeap="10000" eternal="true" timeToIdleSeconds="300" timeToLiveSeconds="600"
overflowToDisk="true" maxEntriesLocalDisk="100000"/>
</ehcache>
mapper.xml
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
pom.xml
<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.googlecode.ehcache-spring-annotations/ehcache-spring-annotations -->
<dependency>
<groupId>com.googlecode.ehcache-spring-annotations</groupId>
<artifactId>ehcache-spring-annotations</artifactId>
<version>1.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>
serviceImpl.java
@Cacheable(value = "myCache", key = "'selectForestInfo'")
@CachePut(value="myCache",key="#updateIntroConfig")//更新myCache 缓存
/**
* XXX.com Inc.
* Copyright (c) 2004-2014 All Rights Reserved.
*/
package com.test.encache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
*
* @author XXX
* @version $Id: EncacheTest.java, v 0.1 2014年8月8日 下午5:30:03 XXX Exp $
*/
public class EncacheTest {
//一些配置参数
//private final static String configFileName = "ehcache.xml";
//private final static int maxEntriesLocalHeap = 1000;
private static CacheManager cacheManager;
static String cacheName = "cache1";
public static void main(String[] args) {
ehcacheSetUp();
ehcacheUse();
}
private static void ehcacheSetUp() {
cacheManager = CacheManager.create();
//CacheConfiguration configuration = new CacheConfiguration(configFileName,
// maxEntriesLocalHeap);
//Cache cache = new Cache(configuration);
cacheManager.addCache(cacheName);
}
private static void ehcacheUse() {
Cache cache1 = cacheManager.getCache(cacheName);
String key = "key1";
String value = "value1";
writeSomeData(cache1, key, value);
Element element = readSomeData(cache1, key, value);
System.out.println(element);
}
private static void writeSomeData(Cache cache, String key, String value) {
cache.put(new Element(key, value));
}
private static Element readSomeData(Cache cache, String key, String value) {
return cache.get(key);
}
}