Ehcache缓存 --- 简单入门

一、Ehcache介绍

 

Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。

Ehcache最初是由Greg Luck于2003年开始开发。2009年,该项目被Terracotta购买。软件仍然是开源,但一些新的主要功能(例如,快速可重启性之间的一致性的)只能在商业产品中使用,例如Enterprise EHCache and BigMemory。维基媒体Foundationannounced目前使用的就是Ehcache技术。

 

 

二、Ehcache特性

  1. 快速
  2. 简单
  3. 缓存数据有两级:内存和磁盘,因此无需担心容量问题
  4. 缓存数据会在虚拟机重启的过程中写入磁盘
  5. 可以通过RMI、可插入API等方式进行分布式缓存
  6. 具有缓存和缓存管理器的侦听接口
  7. 支持多缓存管理器实例,以及一个实例的多个缓存区域
  8. 提供Hibernate的缓存实现
  9. 多种缓存策略,Ehcache提供了对大数据的内存和硬盘的存储,最近版本允许多实例、保存对象高灵活性、提供LRU、LFU、FIFO淘汰算法,基础属性支持热配置、支持的插件多

 

 

三、Ehcache缺点

  1. 使用磁盘Cache的时候非常占用磁盘空间:这是因为DiskCache的算法简单,该算法简单也导致Cache的效率非常高。它只是对元素直接追加存储。因此搜索元素的时候非常的快。如果使用DiskCache的,在很频繁的应用中,很快磁盘会满。
  2. 不能保证数据的安全:当突然kill掉java的时候,可能会产生冲突,EhCache的解决方法是如果文件冲突了,则重建cache。这对于Cache数据需要保存的时候可能不利。当然,Cache只是简单的加速,而不能保证数据的安全。如果想保证数据的存储安全,可以使用Bekeley DB Java Edition版本。这是个嵌入式数据库。可以确保存储安全和空间的利用率。

 

 

四、Ehcache参数配置

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <diskStore path="E:/ehcache"/>

	<!--
		maxElementsInMemory:缓存中允许创建的最大对象数
		eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
		timeToIdleSeconds=y:缓存创建以后,最后一次访问缓存的日期至失效之时的时间间隔y;
		timeToLiveSeconds=x:缓存自创建日期起至失效时的间隔时间x;
		overflowToDisk:内存不足时,是否启用磁盘缓存。
		maxElementsOnDisk:硬盘最大缓存个数。 
	-->
    <defaultCache 
    	maxElementsInMemory="1000" 
    	eternal="false" 
    	timeToIdleSeconds="300" 
    	timeToLiveSeconds="600"
        overflowToDisk="true" 
        maxElementsOnDisk="10000000" />
    
    <!-- 系统缓存 -->
    <!-- 
    	name: 缓存名称
    	maxElementsInMemory:缓存中允许创建的最大对象数
    	eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。 
    	overflowToDisk:内存不足时,是否启用磁盘缓存。 
     -->
    <cache 
    	name="sysCache" 
    	maxElementsInMemory="1000" 
    	eternal="true" 
    	overflowToDisk="true"/>

	<!-- 
		name: 缓存名称
		maxElementsInMemory:缓存中允许创建的最大对象数
		eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
		timeToIdleSeconds=y:缓存创建以后,最后一次访问缓存的日期至失效之时的时间间隔y;
		timeToLiveSeconds=x:缓存自创建日期起至失效时的间隔时间x;
		overflowToDisk:内存不足时,是否启用磁盘缓存。
		maxElementsOnDisk:硬盘最大缓存个数。
		diskPersistent:是否缓存虚拟机重启期数据
		diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
		memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存 
			缓存的3种清空策略:
			LRU---Least Recently Used(最近最少使用)---ehcache默认策略:缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
			LFU---Less Frequently Used(最少使用):一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存。
			FIFO---First In First Out(先进先出)
	 
	 -->
	<cache
		name="categoryCache" 
		maxElementsInMemory="10000"
		eternal="false"
		timeToIdleSeconds="120"
		timeToLiveSeconds="120"
		overflowToDisk="true"
		maxElementsOnDisk="10000000"
		diskPersistent="false"
		diskExpiryThreadIntervalSeconds="120"
		memoryStoreEvictionPolicy="LRU"
		/>
</ehcache>
	-->
    <defaultCache 
    	maxElementsInMemory="1000" 
    	eternal="false" 
    	timeToIdleSeconds="300" 
    	timeToLiveSeconds="600"
        overflowToDisk="true" 
        maxElementsOnDisk="10000000" />
    
    <!-- 系统缓存 -->
    <!-- 
    	name: 缓存名称
    	maxElementsInMemory:缓存中允许创建的最大对象数
    	eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。 
    	overflowToDisk:内存不足时,是否启用磁盘缓存。 
     -->
    <cache 
    	name="sysCache" 
    	maxElementsInMemory="1000" 
    	eternal="true" 
    	overflowToDisk="true"/>

	<!-- 
		name: 缓存名称
		maxElementsInMemory:缓存中允许创建的最大对象数
		eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
		timeToIdleSeconds=y:缓存创建以后,最后一次访问缓存的日期至失效之时的时间间隔y;
		timeToLiveSeconds=x:缓存自创建日期起至失效时的间隔时间x;
		overflowToDisk:内存不足时,是否启用磁盘缓存。
		maxElementsOnDisk:硬盘最大缓存个数。
		diskPersistent:是否缓存虚拟机重启期数据
		diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
		memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存 
			缓存的3种清空策略:
			LRU---Least Recently Used(最近最少使用)---ehcache默认策略:缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
			LFU---Less Frequently Used(最少使用):一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存。
			FIFO---First In First Out(先进先出)
	 
	 -->
	<cache
		name="categoryCache" 
		maxElementsInMemory="10000"
		eternal="false"
		timeToIdleSeconds="120"
		timeToLiveSeconds="120"
		overflowToDisk="true"
		maxElementsOnDisk="10000000"
		diskPersistent="false"
		diskExpiryThreadIntervalSeconds="120"
		memoryStoreEvictionPolicy="LRU"
		/>
</ehcache>

 

 

 

五、Ehcache准备环境

(1)引入Ehcache依赖的jar

  • ehcache-2.10.1.jar
  • log4j-1.2.16.jar
  • slf4j-api-1.7.7.jar
  • slf4j-jdk14-1.7.7.jar
  • slf4j-log4j12-1.7.2.jar

(2)在src目录下创建ehcache.xml配置文件

 

六、实例

//读取配置文件:通过类加载器访问配置文件
		CacheManager cacheManager = CacheManager.create(
				CategoryServiceImpl.class.getClassLoader().getResourceAsStream("ehcache.xml"));
		
		//从配置文件中获取名称为categoryCache缓存区
		Cache cache = cacheManager.getCache("categoryCache");
		
		//判断缓存中是否有list集合
		Element element = cache.get("list");
		List<Category> list = null;
		if(element == null){
			//缓存中没有数据
			System.out.println("==========缓存中没有数据,查询数据库==========");
			CategoryDao categoryDao = (CategoryDao) BeanFactory.getBean("categoryDao");
			list = categoryDao.findAll();
			element = new Element("list", list);
			cache.put(element);
			
		}else{
			//缓存中已有数据
			System.out.println("==========缓存中有数据,没有查询数据库==========");
			list = (List<Category>) element.getObjectValue();
		}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
本工程用于研究如何借助Ehcache缓存框架实现对页面的缓存 本工程编码方式:UTF-8 本工程开发工具:MyEclipse 说明: 1、ehcache.xml和ehcache.xsd两个文件可以在下在下载下来的名为“ehcache-core-x.x.x-distribution.tar.gz”压缩文件中找到 2、由于要实现Ehcache缓存页面,所以必须要添加“ehcache-web-2.0.4.jar” jar包,该jar包主要用于辅助Ehcache实现页面缓存 注意: 本web工程的发布不要使用Tomcat7,否则会出现如下异常: 2015-3-25 9:53:50 org.apache.catalina.loader.WebappClassLoader loadClass 信息: Illegal access: this web application instance has been stopped already. Could not load net.sf.ehcache.store.disk.DiskStore$KeySet. The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact. java.lang.IllegalStateException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1600) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559) at net.sf.ehcache.store.disk.DiskStore.keySet(DiskStore.java:560) at net.sf.ehcache.store.disk.DiskStorageFactory$DiskExpiryTask.run(DiskStorageFactory.java:838) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441) at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:317) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:150) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:98) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:181) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:205) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) 相关jar包下载地址: Ehcache 对象、数据缓存:http://ehcache.org/downloads/destination?name=ehcache-core-2.5.2-distribution.tar.gz&bucket=tcdistributions&file=ehcache

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值