`
刘小小尘
  • 浏览: 61714 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

自己动手写ehcache工具类和配置文件ehcache.xml

 
阅读更多

以下代码为ehcache的工具类代码,仅作参考

package com.pzoom.ehcache.util;

/*
 * 生成ehcache的实例,获取cache,调用getCrabmanCache就可以获取cache进行使用
 */
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.apache.log4j.Logger;


public class EhCacheUtil {
	private static Cache brandKeywordMonitorCache;
	private static Cache httpStatusCache;
	private static CacheManager manager;
	private static EhCacheUtil instance;
	private static Logger log = Logger.getLogger(EhCacheUtil.class);

	static {
//		init();
	}

	public static Cache getBrandKeywordMonitorCache() {
		return brandKeywordMonitorCache;
	}
	
	public static Cache getHttpStatusCache() {
		return httpStatusCache;
	}

	public static CacheManager getManager() {
		return manager;
	}

	public static EhCacheUtil init() {
		log.debug("[EhcacheUtil.init]");
		System.setProperty("net.sf.ehcache.enableShutdownHook","true");
		if (instance == null) {
			
			instance = new EhCacheUtil();
			manager = CacheManager.create(EhCacheUtil.class.getClassLoader().getResourceAsStream("ehcache.xml"));
			
			brandKeywordMonitorCache = manager.getCache("BrandKeywordMonitorCache");
			httpStatusCache=manager.getCache("HttpStatusCache");
		}
		return instance;

	}
	
	public static EhCacheUtil init(String path) {
		log.debug("[EhcacheUtil.init]");
		System.setProperty("net.sf.ehcache.enableShutdownHook","true");
		if (instance == null) {
			
			instance = new EhCacheUtil();
			manager = CacheManager.create(EhCacheUtil.class.getClassLoader().getResourceAsStream(path));
			
			brandKeywordMonitorCache = manager.getCache("BrandKeywordMonitorCache");
			httpStatusCache=manager.getCache("HttpStatusCache");
		}
		return instance;

	}
	
	private static boolean isNull(Element e)
	{
		return e==null||e.getObjectValue()==null||e.getValue()==null;
	}

	/**
	 * 存入
	 * @param <T>
	 * @param cache 缓存库
	 * @param key   键
	 * @param value 值
	 */
	public static <T extends Serializable> void put(Cache cache, String key, T value) {
		Element e = new Element(key, value);
		cache.put(e);
		cache.flush() ;
	}
	
	/**
	 * 存入 并设置元素是否永恒保存
	 * @param <T>
	 * @param cache 缓存库
	 * @param key   键
	 * @param value 值
	 */
	public static <T extends Serializable> void put(Cache cache, String key, T value, boolean eternal) {
		Element element = new Element(key, value);
		element.setEternal(eternal);
		cache.put(element);
		cache.flush() ;
	}
	
	/**
	 * 存入
	 * @param <T>
	 * @param cache 缓存库
	 * @param key   键
	 * @param value 值
	 * @param timeToLiveSeconds 最大存活时间
	 * @param timeToIdleSeconds 最大访问间隔时间
	 */
	public static <T extends Serializable> void put(Cache cache, String key, T value,int timeToLiveSeconds,int timeToIdleSeconds) {
		Element element = new Element(key, value);
		element.setTimeToLive(timeToLiveSeconds);
		element.setTimeToIdle(timeToIdleSeconds);
		cache.put(element);
		cache.flush() ;
	}
	
	public static Object getCacheElement(Cache cache, String key) {
		Element e=cache.get(key);
		return e;
	}
	
	public static Object get(Cache cache, String key) {
		Element e=cache.get(key);
		if(e!=null)
		{
			return e.getObjectValue();
		}
		return null;
	}
	
	public static void remove(Cache cache, String key) {
		cache.remove(key);
	}
	
	public static void removeAll(Cache cache, Collection<String> keys) {
		cache.removeAll(keys);
	}

	@SuppressWarnings("unchecked")
	public static void addToList(Cache cache, String key, Serializable value) {
//		if("dailytaskidpingpailist".equals(key))
//		{
//			log.warn(value);
//			new Exception().printStackTrace();
//		}
		Element e = cache.get(key);
		if (isNull(e)) {
			List<Serializable> list =  Collections.synchronizedList(new LinkedList<Serializable>());
			list.add(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		} else {
			List<Serializable> list = (List<Serializable>) e.getObjectValue();
			list.add(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		}
		
		cache.flush() ;
	}
	
	@SuppressWarnings("unchecked")
	public static void addAllToList(Cache cache, String key, Collection<? extends Serializable> value) {
		Element e = cache.get(key);
		if (isNull(e)) {
			List<Serializable> list =  Collections.synchronizedList(new LinkedList<Serializable>());
			list.addAll(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		} else {
			List<Serializable> list = (List<Serializable>) e.getObjectValue();
			list.addAll(value);
			log.debug(key+"--"+list);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		}
		
		cache.flush() ;
	}
	
	@SuppressWarnings("unchecked")
	public static void addToHashSet(Cache cache, String key, Serializable value) {
		Element e = cache.get(key);
		if (isNull(e)) {
			Set<Serializable> list =  Collections.synchronizedSet(new HashSet<Serializable>());
			list.add(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		} else {
			Set<Serializable> list = (Set<Serializable>) e.getObjectValue();
			list.add(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		}
		
		cache.flush() ;
	}
	
	@SuppressWarnings("unchecked")
	public static void addAllToHashSet(Cache cache, String key, Collection<? extends Serializable> value) {
		Element e = cache.get(key);
		if (isNull(e)) {
			Set<Serializable> list =  Collections.synchronizedSet(new HashSet<Serializable>());
			list.addAll(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		} else {
			Set<Serializable> list = (Set<Serializable>) e.getObjectValue();
			list.addAll(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		}
		
		cache.flush() ;
	}
	
	@SuppressWarnings("unchecked")
	public static void addToArrayList(Cache cache, String key, Serializable value) {
		Element e = cache.get(key);
		if (isNull(e)) {
			List<Serializable> list =  Collections.synchronizedList(new ArrayList<Serializable>());
			list.add(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		} else {
			List<Serializable> list =  (List<Serializable>) e.getObjectValue();
			list.add(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		}
		
		cache.flush() ;
	}
	
	@SuppressWarnings("unchecked")
	public static void addAllToArrayList(Cache cache, String key, Collection<? extends Serializable> value) {
		Element e = cache.get(key);
		if (isNull(e)) {
			List<Serializable> list =  Collections.synchronizedList(new ArrayList<Serializable>());
			list.addAll(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		} else {
			List<Serializable> list =  (List<Serializable>) e.getObjectValue();
			list.addAll(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		}
		
		cache.flush() ;
	}
	
	@SuppressWarnings("unchecked")
	public static <T extends Serializable> T popFromList(Cache cache, String key, Class<T> T)
	{
		Element e=cache.get(key);
		if(e!=null)
		{
			List<Serializable> list=(List<Serializable>) e.getObjectValue();
			Iterator<Serializable> it=list.iterator();
			if(list.size()>0)
			{
				Serializable obj=it.next();
				it.remove();
				e=new Element(key,list);
				e.setEternal(true);
				cache.put(e);
				cache.flush() ;
				return (T) obj;
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T extends Serializable> List<T> popFromList(Cache cache, String key,
			int count, Class<T> T) {
		Element e = cache.get(key);
		if (e != null) {
			List<Serializable> list = (List<Serializable>) e.getObjectValue();
			
			if(count<1)
			{
				List<T> result = (List<T>) new ArrayList<Serializable>(list);
				list.clear();
				e = new Element(key, list);
				e.setEternal(true);
				cache.put(e);
				cache.flush() ;
				return result;
			}
			
			List<T> result = new ArrayList<T>(count);
			Iterator<Serializable> it=list.iterator();
			for (int i = 0; i < count && it.hasNext(); i++) {
				Serializable obj = it.next();
				it.remove();
				result.add((T) obj);
			}
			
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
			cache.flush() ;
			return result;
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static <T extends Serializable> T popFromHashSet(Cache cache, String key, Class<T> T)
	{
		Element e=cache.get(key);
		if(e!=null)
		{
			Set<Serializable> list=(Set<Serializable>) e.getObjectValue();
			Iterator<Serializable> it=list.iterator();
			if(list.size()>0)
			{
				Serializable obj=it.next();
				it.remove();
				e=new Element(key,list);
				e.setEternal(true);
				cache.put(e);
				cache.flush() ;
				return (T) obj;
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T extends Serializable> List<T> popFromHashSet(Cache cache, String key,
			int count, Class<T> T) {
		Element e = cache.get(key);
		if (e != null) {
			Set<Serializable> list = (Set<Serializable>) e.getObjectValue();
			
			if(count<1)
			{
				List<T> result = (List<T>) new ArrayList<Serializable>(list);
				list.clear();
				e = new Element(key, list);
				e.setEternal(true);
				cache.put(e);
				cache.flush() ;
				return result;
			}
			
			List<T> result = new ArrayList<T>(count);
			Iterator<Serializable> it=list.iterator();
			for (int i = 0; i < count && it.hasNext(); i++) {
				Serializable obj = it.next();
				it.remove();
				result.add((T) obj);
			}
			
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
			cache.flush() ;
			return result;
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static int getCollectionSize(Cache cache, String key) {
		Element e = cache.get(key);
		if (e != null) {
			Collection<Serializable> list = (Collection<Serializable>) e.getObjectValue();
			return list.size();
		}
		return 0;
	}
	
	@SuppressWarnings("rawtypes")
	public static List getKeys(Cache cache) {
		return cache.getKeys();
	}
	
	public static List<String> getKeys(Cache cache, String start) {
		List<?> list=cache.getKeys();
		List<String> result=new ArrayList<String>(list.size());
		for(Object obj:list)
		{
			if(obj!=null&&obj.getClass()==String.class)
			{
				String s=(String) obj;
				if(s.startsWith(start))
					result.add(s);
			}
		}
		return result;
	}
	
	public static void main(String[] args)
	{
		init() ;
		put(httpStatusCache, "xiaochen", "a") ;
		List<String> list = new ArrayList<String>() ;
		list.add("b") ;
		list.add("c") ;
		list.add("d") ;
		
		put(httpStatusCache, "xiaochen", "b") ;
		put(httpStatusCache, "xiaochen", "c") ;
		
		Element aaaa = new Element("xiaohan", list) ;
		httpStatusCache.put(aaaa) ;
		
		Element element = httpStatusCache.get("xiaochen") ;
		
		Element aaaaa = httpStatusCache.get("xiaohan") ;
		System.out.println("aaaa : " + aaaaa.getValue());
		
		System.out.println("** : " + element.getValue());
		
		System.out.println("keys : " + httpStatusCache.getKeys().size());
		System.out.println("keys : " + httpStatusCache.getKeys().get(1));
		int a = 10 ;
		assert a==10 : "Out assertion failed!" ;
		
		element.getValue() ;
		
	}
}

ehcache.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
	<!-- 设置磁盘持久化的位置 -->
	<diskStore path="E:/temp" /> 
	<defaultCache maxElementsInMemory="10000" eternal="true"
        overflowToDisk="true" />
    <cache name="BrandKeywordMonitorCache"

           maxElementsInMemory="0"

           maxElementsOnDisk="90000" 
			
           eternal="false" 

           overflowToDisk="true" 

           diskSpoolBufferSizeMB="2048"

           timeToIdleSeconds="7200" 
           timeToLiveSeconds="7200" 
           memoryStoreEvictionPolicy="LFU"
           diskPersistent="true" 
           logging="false"
            />
     <cache name="HttpStatusCache"

           maxElementsInMemory="0"

           maxElementsOnDisk="90000" 
			
           eternal="false"
           overflowToDisk="true" 
           diskSpoolBufferSizeMB="2048"
           diskExpiryThreadIntervalSeconds="120"
           diskPersistent="true" 
		
           timeToIdleSeconds="7200" 
           timeToLiveSeconds="7200" 
           memoryStoreEvictionPolicy="LFU"
           
           logging="false"
            />
    <cache name="CrabmanCacheALL"

           maxElementsInMemory="90000"

           maxElementsOnDisk="90000" 
			
           eternal="false" 

           overflowToDisk="true" 

           diskSpoolBufferSizeMB="2048"

           timeToIdleSeconds="7200" 
           timeToLiveSeconds="7200" 
           memoryStoreEvictionPolicy="LFU"
           diskPersistent="true" 
            />        
</ehcache> 

分享到:
评论

相关推荐

    Spring+MyBatis/Hibernate+Ehcache+Maven的Demo Web项目(稳定版)

    见applicationContext-cache.xml及web.xml的pageEhCacheFilter 4.MyBatis+Maven代码生成工具。见bin目录 5.作为项目或者技术研究的基础架构。必要的jar包依赖都已配置好,基本都采用较新版本,花了好几天时间去测试...

    Spring+MyBatis/Hibernate+Ehcache+Maven的Demo Web项目

    见applicationContext-cache.xml及web.xml的pageEhCacheFilter 4.MyBatis+Maven代码生成工具。见bin目录 5.作为项目或者技术研究的基础架构。必要的jar包依赖都已配置好,基本都采用较新版本,花了好几天时间去测试...

    spring-struts1-strust2-hibernate 核心包介绍

    这个jar文件包含Spring框架基本的核心工具类,Spring其它组件要都要使用到这个包里的类,是其它组件的基本核心,当然你也可以在自己的应用系统中使用这些工具类。 (2) spring-beans.jar 这个jar文件是所有应用...

    web开发常用jar

    Hibernate使用dom4j解析XML配置文件和XML映射元文件。必需的。 ehcache-1.2.jar Hibernate可以使用不同cache缓存工具作为二级缓存。EHCache是缺省的cache缓存工具。如果没有其它的可选缓存工具,则为必需的。 ...

    java开发常用jar包

    Hibernate使用dom4j解析XML配置文件和XML映射元文件。必需的。 ehcache-1.2.jar Hibernate可以使用不同cache缓存工具作为二级缓存。EHCache是缺省的cache缓存工具。如果没有其它的可选缓存工具,则为必需的。 ...

    JAVA上百实例源码以及开源项目

     Java访问权限控制,为Java操作文件、写入文件分配合适的权限,定义写到文件的信息、定义文件,输出到c:/hello.txt、写信息到文件、关闭输出流。 Java绘制图片火焰效果 1个目标文件 摘要:Java源码,图形操作,火焰...

    JAVA上百实例源码以及开源项目源代码

     Java访问权限控制,为Java操作文件、写入文件分配合适的权限,定义写到文件的信息、定义文件,输出到c:/hello.txt、写信息到文件、关闭输出流。 Java绘制图片火焰效果 1个目标文件 摘要:Java源码,图形操作,火焰...

    spring4.1核心包

    包含Web应用开发时,用到Spring框架时所需的核心类,包括自动载入WebApplicationContext特性的类、Struts与JSF集成类、文件上传的支持类、Filter类和大量工具辅助类。 18. spring-webmvc-4.1.1.RELEASE.jar 包含...

    java开源包101

    ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能文件(包括上传和下 载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括...

    java开源包10

    ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能文件(包括上传和下 载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括...

    java开源包1

    ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能文件(包括上传和下 载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括...

    java开源包11

    ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能文件(包括上传和下 载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括...

    java开源包2

    ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能文件(包括上传和下 载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括...

    java开源包3

    ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能文件(包括上传和下 载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括...

    java开源包6

    ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能文件(包括上传和下 载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括...

    java开源包5

    ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能文件(包括上传和下 载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括...

    java开源包4

    ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能文件(包括上传和下 载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括...

    java开源包8

    ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能文件(包括上传和下 载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括...

    java开源包7

    ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能文件(包括上传和下 载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括...

Global site tag (gtag.js) - Google Analytics