自己动手写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>
相关推荐
总的来说,Ehcache是一个强大的工具,能够帮助提升Java应用的性能,通过合理配置和使用,可以有效地管理缓存,避免频繁的数据库交互,从而提高系统响应速度。记住,优化缓存的关键在于理解业务需求和数据访问模式,...
- **配置**:EHCache的配置文件通常为`ehcache.xml`,包含缓存的大小、过期策略、缓存区配置等。开发者可以根据实际需求定制配置。 - **API使用**:在Java代码中,可以通过`CacheManager`、`Cache`等类来创建、获取...
3. **配置Ehcache**:创建Ehcache的配置文件`ehcache.xml`,并放置在项目的类路径下。这个文件定义了缓存的策略,如缓存大小、存活时间等。一个简单的配置示例如下: ```xml <ehcache xmlns:xsi=...
标题中的"ehcache开发工具包"指的是用于集成和管理EhCache的资源集合,通常包含EhCache的JAR库文件、相关的配置文件和版本信息等。在给定的压缩包中,我们看到有以下四个文件: 1. `ehcache-1.6.2.jar`: 这是...
`ehcache.xml`是Ehcache的配置文件,它定义了缓存的设置,如缓存大小、存活时间和过期时间等。在MyBatis-Ehcache集成中,这个配置文件通常会被MyBatis读取,以指导缓存行为。通过调整`ehcache.xml`中的参数,开发者...
4. 配置Ehcache的配置文件(`ehcache.xml`),定义缓存区域、大小、存活时间和过期策略等。 5. 在代码中正确操作缓存,例如清理缓存、控制缓存更新等。 **注意事项**: - 缓存不是万能的,不恰当的使用可能会导致数据...
- 使用:通过注解或配置XML文件,可以指定哪些实体类或查询结果应该被缓存。 4. 文件"ehcache-core-2.6.2"分析: 这个压缩包很可能是EhCache 2.6.2版本的核心库,包含了EhCache运行所需的所有类和资源。开发者...
2. **配置Ehcache**: 在项目中创建`ehcache.xml`配置文件,定义缓存的属性,如缓存的大小、存活时间和过期时间。例如: ```xml maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="120" ...
接着,我们需要创建一个Ehcache配置文件(ehcache.xml),定义缓存策略和缓存区域。例如: ```xml <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation=...
配置文件通常放在类路径下,可以通过`net.sf.ehcache.config.Configuration.fromXML()`方法加载。 2. **缓存对象**: 使用`CacheManager`实例来管理缓存,创建`Cache`对象并添加到`CacheManager`中。`Cache`对象是...
- **配置Ehcache**:创建ehcache.xml配置文件,设置缓存策略、大小、过期时间等。 - **配置Hibernate**:在hibernate.cfg.xml或对应的配置文件中,启用二级缓存并指定使用Ehcache。 - **实体类注解**:在需要缓存的...
通过理解和配置`hibernate.cfg.xml`文件,开发者可以自定义数据库连接、实体类、缓存策略等,从而更好地利用Hibernate的强大功能。同时,这些jar包涵盖了从对象持久化到数据库操作、事务管理、日志记录等多个方面,...
4. **配置文件**:`ehcache`通过XML配置文件进行初始化设置,包括缓存大小、内存和磁盘存储策略、缓存加载策略等。用户可以根据需求自定义配置,以适应不同的应用场景。 5. **缓存策略**:`ehcache`支持多种缓存...
3. 拷贝Ehcache配置文件:将Ehcache的配置文件(ehcache.xml)放入类路径,通常是项目源码目录(src/main/resources)下。这个配置文件定义了缓存的策略、大小、过期时间等参数,可以根据实际需求进行定制。 三、...
这里以XML配置为例,创建一个名为`ehcache.xml`的配置文件: ```xml <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> ...
接下来,我们需要创建一个Ehcache配置文件,例如ehcache.xml,定义缓存的属性,如大小、存活时间等。例如: ```xml <config xmlns="http://www.ehcache.org/v3"> <key-type>java.lang.String <value-type>java....
配置文件可能是XML格式,例如`ehcache.xml`,在其中定义了缓存的各个属性。 4. **查询缓存**:除了普通的数据缓存,Ehcache还提供了查询缓存功能,它可以缓存查询结果,避免重复执行相同的查询操作。这对于数据库...
然后,在Hibernate的配置文件(如hibernate.cfg.xml)中启用二级缓存并指定Ehcache配置文件: ```xml <property name="hibernate.cache.use_second_level_cache">true <property name="hibernate.cache.region....
2. **配置Ehcache**:创建XML配置文件,定义缓存的名称、大小、过期策略等参数。 3. **初始化Ehcache**:在应用程序启动时加载配置并初始化Ehcache实例。 4. **使用缓存**:通过Ehcache API进行缓存的增删查改操作...
在使用这些jar包构建Ehcache系统时,需要确保它们都包含在类路径中,并正确配置Ehcache的XML配置文件。配置文件可以定义缓存的大小、过期策略、缓存分区、 Terracotta集群设置等。此外,还应考虑与其他依赖项(如...