import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import cn.com.btmu.art.framework.exception.sysexception.BizParameterException;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
* 缓存方法
*
* */
public class CacheUtil {
private static CacheManager cacheManager = null;
/**实例化CacheManager对象
* 得到配置文件路径
* new CacheManager
* @param String cacheUrl
* @return CacheManager
* */
public static CacheManager initCache(String cacheUrl) {
try{
URL url;
if(StringUtils.isNotEmpty(cacheUrl)){
url = CacheUtil.class.getClassLoader().getResource(
cacheUrl);
}else{
url = CacheUtil.class.getClassLoader().getResource( “cn/com/btmu/art/framework/common/cache/config/ehcache.xml”);
}
cacheManager=new CacheManager(url);
}catch(Exception e){
throw new BizParameterException("输入路径"+cacheUrl+"格式错误,请检查!",e);
}
return cacheManager;
}
/**
* 初始化缓存管理容器
* */
public static CacheManager getCacheManagerInstance() {
if (null==cacheManager){
synchronized(cacheManager) {
cacheManager = CacheManager.getInstance();
}
}
return cacheManager;
}
/**
* 通过分类缓存名称,获取缓存对象。
* @param String cacheName
* @return Cache
* */
public static Cache getCache(String cacheName){
Cache cache=null;
if(StringUtils.isNotEmpty(cacheName)){
if(null!=cacheManager){
cache=cacheManager.getCache(cacheName);
}
}
return cache;
}
/***
* 为指定分类名称的缓存添加一条缓存记录。
* @param cacheName, key, value
* */
public static void put(String cacheName,String key,Object value){
// 根据缓存名得到缓存对象
Cache cache=getCache(cacheName);
if(null!=cache){
Element element = new Element(key, value);
if(null==element){
throw new BizParameterException("key="+key+"--value="+value+",参数不 能为空!");
}
// put添加缓存
if(null!=element){
synchronized(cacheManager) {
cache.put(element);
}
}
}
}
/**
* 通过缓存分类名称,缓存元素键,获取缓存元素。
* */
public static Object get(String cacheName,String key){
//TODO 根据缓存名得到缓存对象
Cache cache=getCache(cacheName);
Object val = null;
if( null!=cache ){
Element element = cache.get(key);
if(null!=element){
val = element.getObjectValue();
}
}
return val;
}
/**
* 通过分类缓存名称、缓存key,清除缓存记录。
* */
public static void remove(String cacheName,String key){
synchronized(cacheManager) {
//根据缓存名得到缓存对象
Cache cache=getCache(cacheName);
if(null!=cache){
// 根据key remove移除Cache
cache.remove(key);
}
}
}
/***
* 清除指定分类缓存对象的所有缓存记录。
* */
public static void removeAll(String cacheName){
synchronized(cacheManager) {
// 根据缓存名得到缓存对象
Cache cache=getCache(cacheName);
if(null!=cache){
// 移除所有的缓存记录
cache.removeAll();
}
}
}
/**
* 根据缓存name得到一个list集合数据
* @param cacheName
* @return list
* list 的size不能超过两百条
* */
public static List getCacheList(String cacheName){
List list=new ArrayList();
//得到缓存对象
Cache cache=getCache(cacheName);
if(null!=cache){
//得到缓存对象的所有的key
List listKey =cache.getKeys();
Iterator iterator =listKey.iterator();
//if(listKey.size()<=CacheConstant.CACHE_SIZE){
//根据key取出所有的name,把所有的name,key存到list里
/*for (int i = 0; i < listKey.size(); i++) {
list.add(listKey.get(i).toString());
list.add(get(cacheName, listKey.get(i).toString()));
}*/
while(iterator.hasNext()){
String key=(String) iterator.next();
list.add(key);
list.add(get(cacheName,key));
}
}
return list;
}
/**
* 根据缓存name得到一个map集合数据key,value
* @param cacheName
* @return map
* 数据不能超过两百条
* */
public static Map getCacheMap(String cacheName){
Map map=new HashMap();
//得到缓存对象
Cache cache=getCache(cacheName);
if(null!=cache){
//得到缓存对象的所有的key
List listKey =cache.getKeys();
Iterator iterator =listKey.iterator();
//if(listKey.size()<=CacheConstant.CACHE_SIZE){
//根据key取出所有的name,把所有的name,key存到list里
while(iterator.hasNext()){
String key=(String) iterator.next();
map.put(key,(get(cacheName,key)));
}
/*for (int i = 0; i < listKey.size(); i++) {
map.put(listKey.get(i).toString(), get(cacheName, listKey.get(i).toString()));
}*/
}
return map;
}
/**
* 关闭缓存
* */
public static void shutdown() {
synchronized (cacheManager) {
if (null != cacheManager) {
cacheManager.shutdown();
}
}
}
}
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- 第一种简单写法测试-->
<!--
缓存配置
name:缓存名称。
maxElementsInMemory:缓存最大个数。
maxEntriesLocalHeap(必填属性):设置缓存在本地内存中最大缓存项数量(0表示无限)。
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:内存数量最大时是否清除。
-->
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false"
monitoring="autodetect" dynamicConfig="true" clearOnFlush="true">
<!-- <diskStore path="user.home"/>-->
<defaultCache maxElementsInMemory="10000000" maxEntriesLocalHeap="100000" eternal="false"
overflowToDisk="true" timeToIdleSeconds="1200" timeToLiveSeconds="1200">
</defaultCache>
<!-- 业务服务配置 -->
<cache name="ServiceConfiguration" maxEntriesLocalHeap="0"
maxEntriesLocalDisk="1000000" eternal="true" overflowToDisk="false"
diskSpoolBufferSizeMB="30" timeToIdleSeconds="300" timeToLiveSeconds="600"
memoryStoreEvictionPolicy="FIFO" transactionalMode="off" />
</ehcache>
还有一个空内容的 ehcache.xsd