1.maven引入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.5</version>
</dependency>
2.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">
<!-- EhCache library setup -->
<bean id="commonCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:cache/common-ehcache-local.xml"/>
</beans>
3.common-ehcache-local.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="commonCache">
<diskStore path="../temp/picc/common_ehcache" />
<!-- 默认缓存配置. 自动失效:最后一次访问时间间隔300秒失效,若没有访问过自创建时间600秒失效。-->
<defaultCache maxEntriesLocalHeap="1000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600"
overflowToDisk="true" statistics="true"/>
<!-- 系统缓存 -->
<cache name="sysCache" maxEntriesLocalHeap="1000" eternal="true" overflowToDisk="true" statistics="true"/>
</ehcache>
common-ehcache-rmi.xml文件(集群同步)
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="commonCache">
<!--
<cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=manual, socketTimeoutMillis=2000, rmiUrls=//localhost:40001/defaultCache" />
<cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
properties="hostName=localhost, port=40000, socketTimeoutMillis=2000"/> -->
<cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=automatic,multicastGroupAddress=230.0.0.1, multicastGroupPort=4446" />
<cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" />
<diskStore path="../temp/picc/common_ehcache" />
<!-- 默认缓存配置. -->
<defaultCache maxEntriesLocalHeap="1000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600"
overflowToDisk="true" statistics="true">
<cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
properties="replicatePuts=false,replicateUpdatesViaCopy=false"/>
</defaultCache>
<!-- 系统缓存 -->
<cache name="sysCache" maxEntriesLocalHeap="1000" eternal="true" overflowToDisk="true" statistics="true">
<cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/>
</cache>
</ehcache>
4.CommonSpringContextHolder文件
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
/**
* 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
*
*/
@Service
@Lazy(false)
public class CommonSpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext applicationContext = null;
private static Logger logger = LoggerFactory.getLogger(CommonSpringContextHolder.class);
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return applicationContext.getBean(requiredType);
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
if (logger.isDebugEnabled()){
logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
}
applicationContext = null;
}
/**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
CommonSpringContextHolder.applicationContext = applicationContext;
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() throws Exception {
CommonSpringContextHolder.clearHolder();
}
/**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
}
}
5.缓存工具类
import com.xxxx.xxx.util.CommonSpringContextHolder;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Cache工具类
* @author PICC
* @version 2013-5-29
*/
public class CommonCacheUtils {
private static Logger logger = LoggerFactory.getLogger(CommonCacheUtils.class);
private static CacheManager cacheManager = CommonSpringContextHolder.getBean("commonCacheManager");
/**
* 获得一个Cache,没有则显示日志。
* @param cacheName
* @return
*/
private static Cache getCache(String cacheName){
Cache cache = cacheManager.getCache(cacheName);
if (cache == null){
throw new RuntimeException("当前系统中没有定义“"+cacheName+"”这个缓存。");
}
return cache;
}
/**
* 获取缓存键名,多数据源下增加数据源名称前缀
* @param key
* @return
*/
private static String getKey(String key){
// String dsName = DataSourceHolder.getDataSourceName();
// if (StringUtils.isNotBlank(dsName)){
// return dsName + "_" + key;
// }
return key;
}
/**
* 获取缓存
* @param cacheName
* @param key
* @return
*/
public static Object get(String cacheName, String key) {
net.sf.ehcache.Element e = getCache(cacheName).get(getKey(key));
if (e == null) {
return null;
}
return e.getValue();
}
/**
* 从缓存中移除
* @param cacheName
* @param key
*/
public static void remove(String cacheName, String key) {
getCache(cacheName).remove(getKey(key));
}
/**
* 从缓存中移除所有
* @param cacheName
*/
public static void removeAll(String cacheName) {
Cache cache = getCache(cacheName);
cache.removeAll();
logger.info("清理缓存: {} => {}", cacheName);
}
/**
* 写入缓存
* @param cacheName
* @param key
* @param value
*/
public static void put(String cacheName, String key, Object value) {
Element element = new Element(key, value);
getCache(cacheName).put(element);
}
}
6.测试
CommonCacheUtils.put("sysCache","abc",langType);
Map<String,Object> root = new HashMap<String,Object>();
root.put("username", "ajun");
CommonCacheUtils.put("sysCache","map",root);
List<Menu> list = systemService.findAllMenu();
CommonCacheUtils.put("sysCache","list",list);
Object ojb=CommonCacheUtils.get("sysCache","abc");
Object map=CommonCacheUtils.get("sysCache","map");
Object Menu=CommonCacheUtils.get("sysCache","list");