Ehcache使用

<?xml version="1.0" encoding="UTF-8"?>  
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
   xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"  
    updateCheck="false"> 
    <!--updateCheck 是否通过Internet检查Ehcache的新版本 磁盘存储配置:用来指定缓存在磁盘上的存储位置。可以使用JavaVM环境变量(user.home, user.dir, java.io.tmpdir)-->
    
    <diskStore path="user.home" />
    
	<cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" 
		properties="peerDiscovery=manual,
		rmiUrls=//localhost:40001/test" 
		propertySeparator="," />
		
	<cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" 
		properties="hostName=localhost,
		port=40001,		
		socketTimeoutMillis=60000" 
		propertySeparator="," />
		<!--remoteObjectPort=40002, -->
<!-- 不过期 
	在内存中缓存的element的最大数目
	在磁盘上缓存的element的最大数目
	设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上
	缓存element在过期前的空闲时间
	缓存element的有效生命期
	在VM重启的时候是否持久化磁盘缓存,默认是false。
	磁盘缓存的清理线程运行间隔,默认是120秒.
	默认是LRU,可选的有LFU和FIFO
  
-->

<!--  
	name:缓存名称。  
	maxElementsInMemory:缓存最大个数。  1表示无穷大
	eternal:对象是否永久有效,一但设置了,timeout将不起作用。  
	timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。  
	timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。  
	overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。  
	diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。  
	maxElementsOnDisk:硬盘最大缓存个数。  0表示无穷大
	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:内存数量最大时是否清除。  
    -->  
    <defaultCache eternal="false" 
       maxElementsInMemory="10000"  
       maxElementsOnDisk ="0"  
       overflowToDisk="true" 
       timeToIdleSeconds ="3600"  
       timeToLiveSeconds ="0" 
       diskPersistent ="true"
       diskSpoolBufferSizeMB="1024" 
       diskExpiryThreadIntervalSeconds ="300"
       memoryStoreEvictionPolicy ="LRU" />  
<!-- 
	缓存子元素:
	cacheEventListenerFactory:注册相应的的缓存监听类,用于处理缓存事件,如put,remove,update,和expire
	bootstrapCacheLoaderFactory:指定相应的BootstrapCacheLoader,用于在初始化缓存,以及自动设置。
-->     
    <cache name="test" 
    	eternal="false" 
    	maxElementsInMemory="100"  
    	maxElementsOnDisk ="0"  
        overflowToDisk="true" 
        timeToIdleSeconds="3600"  
        timeToLiveSeconds="0" 
        diskPersistent="true" 
        diskSpoolBufferSizeMB="1024" 
        diskExpiryThreadIntervalSeconds ="120"
        memoryStoreEvictionPolicy="LRU" />
   
</ehcache>


package util;

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

public class EHCache { 
	
	private static Cache test =null;
	
	private static Cache getCacheService(){
		if(null==test){
			test=CacheManager.getInstance().getCache("test");
		}
		return test;
	} 
	
	/****
	 * 通过名称从缓存中获取数据
	 * @param cacheKey
	 * @return
	 * @throws Exception
	 */
	public static Object getCacheElement(String cacheKey) throws Exception {
		net.sf.ehcache.Element e = getCacheService().get(cacheKey);
		if (e == null) {
			return null;
		}
		return e.getValue();
	}

	/****
	 * 将对象添加到缓存中
	 * @param cacheKey
	 * @param result
	 * @throws Exception
	 */
	public static void addToCache(String cacheKey, Object result) throws Exception {
		Element element = new Element(cacheKey, result);
		getCacheService().put(element);
	}
	
	/****
	 * 清除所有的缓存
	 */
	public static void clearAllCache(){
		getCacheService().removeAll();
	}  
}  

测试类

import org.json.simple.JSONObject;
import util.EHCache;
public class testcache {
	public static void main(String[] args) throws Exception {
		EHCache.clearAllCache();
		// 测试将json对象存入缓存中
		JSONObject obj = new JSONObject();
		obj.put("name", "foo");
		EHCache.addToCache("jsoncache", obj);
		// 从缓存中获取
		JSONObject getobj1 = (JSONObject) EHCache.getCacheElement("jsoncache");

		System.err.println(getobj1.toString());
	}
}


EHCache API的基本用法
首先介绍 CacheManager类。它主要负责读取配置文件,默认读取CLASSPATH下的ehcache.xml,根据配置文件创建并管理Cache对象。
// 使用默认配置文件创建CacheManager
CacheManager manager = CacheManager.create();
// 通过manager可以生成指定名称的Cache对象
Cache cache = cache = manager.getCache("demoCache");
// 使用manager移除指定名称的Cache对象
manager.removeCache("demoCache");
可以通过调用manager.removalAll()来移除所有的Cache。通过调用manager的shutdown()方法可以关闭CacheManager。

有了 Cache对象之后就可以进行一些基本的Cache操作,例如:
//往cache中添加元素
Element element = new Element("key", "value");
cache.put(element);
//从cache中取回元素
Element element = cache.get("key");
element.getValue();
//从Cache中移除一个元素
cache.remove("key");
可以直接使用上面的API进行数据对象的缓存,这里需要注意的是对于缓存的对象都是必须可序列化的。
在下面的篇幅中笔者还会介绍EHCache和Spring、Hibernate的整合使用。

转载:http://blog.sina.com.cn/s/blog_4e345ce70101my2s.html


ehcache开发包http://download.csdn.net/detail/u010081710/9579068

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然,我可以为您提供关于 Ehcache 的详细教程。以下是使用 Ehcache 的一般步骤: 1. 引入 Ehcache 依赖:在您的项目中,您需要添加 Ehcache 的依赖。可以使用 Maven 或 Gradle 进行管理。以下是 Maven 的配置示例: ```xml <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.8.1</version> </dependency> ``` 2. 创建一个 Ehcache 配置文件:Ehcache 使用 XML 文件来配置缓存。您可以创建一个名为 `ehcache.xml` 的文件,并将其放置在类路径下。以下是一个简单的配置示例: ```xml <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ehcache.org/v3" xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd"> <cache alias="myCache"> <resources> <heap unit="entries">100</heap> <offheap unit="MB">1</offheap> </resources> </cache> </config> ``` 3. 初始化和获取缓存:在您的代码中,您需要初始化 Ehcache 缓存管理器,并获取所需的缓存实例。以下是示例代码: ```java import org.ehcache.Cache; import org.ehcache.CacheManager; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.xml.XmlConfiguration; public class Main { public static void main(String[] args) { XmlConfiguration xmlConfig = new XmlConfiguration(Main.class.getResource("/ehcache.xml")); CacheManager cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig); cacheManager.init(); Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class); myCache.put("key", "value"); String value = myCache.get("key"); System.out.println(value); cacheManager.close(); } } ``` 在上面的示例中,我们首先使用 `XmlConfiguration` 类将 XML 配置文件加载为 `CacheManagerBuilder`。然后,我们使用 `cacheManager` 获取名为 "myCache" 的缓存实例,并将键值对放入缓存。最后,我们从缓存中获取值并打印出来。 这是一个简单的 Ehcache 使用教程。您可以根据自己的需求进行更高级和复杂的配置。希望对您有所帮助!如有任何问题,请随时向我提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值