ehcache 缓存技术
一 ehcache API:
1: Using the CacheManager
1.1所有ehcache的使用, 都是从 CacheManager. 开始的.
有多种方法创建CacheManager实例:
- //Create a singleton CacheManager using defaults, then list caches.
 - CacheManager.getInstance()
 
或者:
- //Create a CacheManager instance using defaults, then list caches.
 - CacheManager manager = new CacheManager();
 - String[] cacheNames = manager.getCacheNames();
 
如果需要从指定配置文件创建 CacheManager:
- Create two CacheManagers, each with a different configuration, and list the caches in each.
 - CacheManager manager1 = new CacheManager("src/config/ehcache1.xml");
 - CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");
 - String[] cacheNamesForManager1 = manager1.getCacheNames();
 - String[] cacheNamesForManager2 = manager2.getCacheNames();
 
1.2 Adding and Removing Caches Programmatically
手动创建一个cache, 而不是通过配置文件:
- //creates a cache called testCache, which
 - //will be configured using defaultCache from the configuration
 - CacheManager singletonManager = CacheManager.create();
 - singletonManager.addCache("testCache");
 - Cache test = singletonManager.getCache("testCache");
 
或者:
- //Create a Cache and add it to the CacheManager, then use it. Note that Caches are not usable until they have
 - //been added to a CacheManager.
 - public void testCreatCacheByProgram()
 - {
 - CacheManager singletonManager = CacheManager.create();
 - Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
 - singletonManager.addCache(memoryOnlyCache);
 - Cache testCache = singletonManager.getCache("testCache");
 - assertNotNull(testCache);
 - }
 
手动移除一个cache:
- //Remove cache called sampleCache1
 - CacheManager singletonManager = CacheManager.create();
 - singletonManager.removeCache("sampleCache1");
 
1.3 Shutdown the CacheManager
ehcache应该在使用后关闭, 最佳实践是在code中显式调用:
- //Shutdown the singleton CacheManager
 - CacheManager.getInstance().shutdown();
 
2 Using Caches
比如我有这样一个cache:
- <cache name="sampleCache1" maxElementsInMemory="10000"
 - maxElementsOnDisk="1000" eternal="false" overflowToDisk="true"
 - diskSpoolBufferSizeMB="20" timeToIdleSeconds="300"
 - timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" />
 
2.1 Obtaining a reference to a Cache
获得该cache的引用:
- String cacheName = "sampleCache1";
 - CacheManager manager = new CacheManager("src/ehcache1.xml");
 - Cache cache = manager.getCache(cacheName);
 
2.2 Performing CRUD operations
下面的代码演示了ehcache的增删改查:
- public void testCRUD()
 - {
 - String cacheName = "sampleCache1";
 - CacheManager manager = new CacheManager("src/ehcache1.xml");
 - Cache cache = manager.getCache(cacheName);
 - //Put an element into a cache
 - Element element = new Element("key1", "value1");
 - cache.put(element);
 - //This updates the entry for "key1"
 - cache.put(new Element("key1", "value2"));
 - //Get a Serializable value from an element in a cache with a key of "key1".
 - element = cache.get("key1");
 - Serializable value = element.getValue();
 - //Get a NonSerializable value from an element in a cache with a key of "key1".
 - element = cache.get("key1");
 - assertNotNull(element);
 - Object valueObj = element.getObjectValue();
 - assertNotNull(valueObj);
 - //Remove an element from a cache with a key of "key1".
 - assertNotNull(cache.get("key1"));
 - cache.remove("key1");
 - assertNull(cache.get("key1"));
 - }
 
2.3 Disk Persistence on demand
- //sampleCache1 has a persistent diskStore. We wish to ensure that the data //and index are written immediately.
 - public void testDiskPersistence()
 - {
 - String cacheName = "sampleCache1";
 - CacheManager manager = new CacheManager("src/ehcache1.xml");
 - Cache cache = manager.getCache(cacheName);
 - for (int i = 0; i < 50000; i++)
 - {
 - Element element = new Element("key" + i, "myvalue" + i);
 - cache.put(element);
 - }
 - cache.flush();
 - Log.debug("java.io.tmpdir = " + System.getProperty("java.io.tmpdir"));
 - }
 
备注: 持久化到硬盘的路径由虚拟机参数"java.io.tmpdir"决定.
例如, 在windows中, 会在此路径下
C:\Documents and Settings\li\Local Settings\Temp
在linux中, 通常会在: /tmp 下
2.4  Obtaining Cache Sizes
以下代码演示如何获得cache个数:
- public void testCachesizes()
 - {
 - long count = 5;
 - String cacheName = "sampleCache1";
 - CacheManager manager = new CacheManager("src/ehcache1.xml");
 - Cache cache = manager.getCache(cacheName);
 - for (int i = 0; i < count; i++)
 - {
 - Element element = new Element("key" + i, "myvalue" + i);
 - cache.put(element);
 - }
 - //Get the number of elements currently in the Cache.
 - int elementsInCache = cache.getSize();
 - assertTrue(elementsInCache == 5);
 - //Cache cache = manager.getCache("sampleCache1");
 - long elementsInMemory = cache.getMemoryStoreSize();
 - //Get the number of elements currently in the DiskStore.
 - long elementsInDiskStore = cache.getDiskStoreSize();
 - assertTrue(elementsInMemory + elementsInDiskStore == count);
 - }
 
3: Registering CacheStatistics in an MBeanServer
ehCache 提供jmx支持:
- CacheManager manager = new CacheManager();
 - MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
 - ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true);
 
把该程序打包, 然后:
- java -Dcom.sun.management.jmxremote -jar 程序名.jar
 
再到javahome/bin中运行jconsole.exe, 便可监控cache.
4. 用户可以自定义处理cacheEventHandler, 处理诸如元素放入cache的各种事件(放入,移除,过期等事件)
只需三步:
4.1 在cache配置中, 增加cacheEventListenerFactory节点.
- <cache name="Test" maxElementsInMemory="1" eternal="false"
 - overflowToDisk="true" timeToIdleSeconds="1" timeToLiveSeconds="2"
 - diskPersistent="false" diskExpiryThreadIntervalSeconds="1"
 - memoryStoreEvictionPolicy="LFU">
 - <cacheEventListenerFactory class="co.ehcache.EventFactory" />
 - </cache>
 
4.2: 编写EventFactory, 继承CacheEventListenerFactory:
- public class EventFactory extends CacheEventListenerFactory
 - {
 - @Override
 - public CacheEventListener createCacheEventListener(Properties properties)
 - {
 - // TODO Auto-generated method stub
 - return new CacheEvent();
 - }
 - }
 
4.3 编写 class: CacheEvent, 实现 CacheEventListener 接口:
- public class CacheEvent implements CacheEventListener
 - {
 - public void dispose()
 - {
 - log("in dispose");
 - }
 - public void notifyElementEvicted(Ehcache cache, Element element)
 - {
 - // TODO Auto-generated method stub
 - log("in notifyElementEvicted" + element);
 - }
 - public void notifyElementExpired(Ehcache cache, Element element)
 - {
 - // TODO Auto-generated method stub
 - log("in notifyElementExpired" + element);
 - }
 - public void notifyElementPut(Ehcache cache, Element element) throws CacheException
 - {
 - // TODO Auto-generated method stub
 - log("in notifyElementPut" + element);
 - }
 - public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException
 - {
 - // TODO Auto-generated method stub
 - log("in notifyElementRemoved" + element);
 - }
 - public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException
 - {
 - // TODO Auto-generated method stub
 - log("in notifyElementUpdated" + element);
 - }
 - public void notifyRemoveAll(Ehcache cache)
 - {
 - // TODO Auto-generated method stub
 - log("in notifyRemoveAll");
 - }
 - public Object clone() throws CloneNotSupportedException
 - {
 - return super.clone();
 - }
 - private void log(String s)
 - {
 - Log.debug(s);
 - }
 - }
 
现在可以编写测试代码:
- public void testEventListener()
 - {
 - String key = "person";
 - Person person = new Person("lcl", 100);
 - MyCacheManager.getInstance().put("Test", key, person);
 - Person p = (Person) MyCacheManager.getInstance().get("Test", key);
 - try
 - {
 - Thread.sleep(10000);
 - }
 - catch (InterruptedException e)
 - {
 - // TODO Auto-generated catch block
 - e.printStackTrace();
 - }
 - assertNull(MyCacheManager.getInstance().get("Test", key));
 - }
 
根据配置, 该缓存对象生命期只有2分钟, 在Thread.sleep(10000)期间, 该缓存元素将过期被销毁, 在销毁前, 触发notifyElementExpired事件.
    
二 Ehcache配置文件
 以如下配置为例说明:
- <cache name="CACHE_FUNC"
 - maxElementsInMemory="2"
 - eternal="false"
 - timeToIdleSeconds="10"
 - timeToLiveSeconds="20"
 - overflowToDisk="true"
 - diskPersistent="true"
 - diskExpiryThreadIntervalSeconds="120" />
 
maxElementsInMemory :cache 中最多可以存放的元素的数量。如果放入cache中的元素超过这个数值,有两种情况:
1. 若overflowToDisk的属性值为true,会将cache中多出的元素放入磁盘文件中。
2. 若overflowToDisk的属性值为false,会根据memoryStoreEvictionPolicy的策略替换cache中原有的元素。
eternal :是否永驻内存。如果值是true,cache中的元素将一直保存在内存中,不会因为时间超时而丢失,所以在这个值为true的时候,timeToIdleSeconds和timeToLiveSeconds两个属性的值就不起作用了。
3. timeToIdleSeconds :访问这个cache中元素的最大间隔时间。如果超过这个时间没有访问这个cache中的某个元素,那么这个元素将被从cache中清除。
4. timeToLiveSeconds : cache中元素的生存时间。意思是从cache中的某个元素从创建到消亡的时间,从创建开始计时,当超过这个时间,这个元素将被从cache中清除。
5. overflowToDisk :溢出是否写入磁盘。系统会根据标签<diskStore path="java.io.tmpdir"/> 中path的值查找对应的属性值,如果系统的java.io.tmpdir的值是 D:\temp,写入磁盘的文件就会放在这个文件夹下。文件的名称是cache的名称,后缀名的data。如:CACHE_FUNC.data。
6. diskExpiryThreadIntervalSeconds :磁盘缓存的清理线程运行间隔.
7. memoryStoreEvictionPolicy :内存存储与释放策略。有三个值:
LRU -least recently used
LFU -least frequently used
FIFO-first in first out, the oldest element by creation time
diskPersistent : 是否持久化磁盘缓存。当这个属性的值为true时,系统在初始化的时候会在磁盘中查找文件名为cache名称,后缀名为index的的文件,如CACHE_FUNC.index 。这个文件中存放了已经持久化在磁盘中的cache的index,找到后把cache加载到内存。要想把cache真正持久化到磁盘,写程序时必须注意,在是用net.sf.ehcache.Cache的void put (Element element)方法后要使用void flush()方法。
 更多说明可看ehcache自带的ehcache.xml的注释说明.
ehcache 缓存技术的更多相关文章
- ehcache缓存技术的特性
		
Ehcache是现在最流行的纯Java开源缓存框架,配置简单.结构清晰.功能强大,最初知道它,是从hibernate的缓存开始的.网上中文的EhCache材料以简单介绍和配置方法居多,如果你有这方面的 ...
 - 网站缓存技术总结( ehcache、memcache、redis对比)
		
网站技术高速发展的今天,缓存技术已经成为大型网站的一个关键技术,缓存设计好坏直接关系的一个网站访问的速度,以及购置服务器的数量,甚至影响到用户的体验. 网站缓存按照存放的地点不同,可以分为客户端缓存. ...
 - JAVA缓存技术之EhCache
		
最近再ITEYE上看到关于讨论JAVA缓存技术的帖子比较多,自己不懂,所以上网大概搜了下,找到一篇,暂作保存,后面如果有用到可以参考.此为转贴,帖子来处:http://cogipard.info/ar ...
 - JAVA缓存技术之EhCache(转)
		
最近再ITEYE上看到关于讨论JAVA缓存技术的帖子比较多,自己不懂,所以上网大概搜了下,找到一篇,暂作保存,后面如果有用到可以参考.此为转贴,帖子来处:http://cogipard.info/ar ...
 - 网站缓存技术(Redis、Memcached、Ehcache)
		
Redis 是什么? 通常而言目前的数据库分类有几种,包括 SQL/NSQL,,关系数据库,键值数据库等等等. 分类的标准也不一,Redis本质上也是一种键值数据库的,但它在保持键值数据库简单快捷特点 ...
 - MyBatis加强(1)~缓存机制(一级缓存、二级缓存、第三方缓存技术redis、ehcache)
		
一.缓存机制 使用缓存可以使应用更快地获取数据,避免频繁的数据库交互操作,尤其是在查询越多,缓存命中率越高 的情况下,缓存的作用就越明显. 1.缓存原理:Map ■ 查询时,先从缓存区查询:找到,返回 ...
 - [原创]mybatis中整合ehcache缓存框架的使用
		
mybatis整合ehcache缓存框架的使用 mybaits的二级缓存是mapper范围级别,除了在SqlMapConfig.xml设置二级缓存的总开关,还要在具体的mapper.xml中开启二级缓 ...
 - 深入探讨在集群环境中使用 EhCache 缓存系统
		
EhCache 缓存系统简介 EhCache 是一个纯 Java 的进程内缓存框架,具有快速.精干等特点,是 Hibernate 中默认的 CacheProvider. 下图是 EhCache 在应用 ...
 - (转)java缓存技术,记录
		
http://blog.csdn.net/madun/article/details/8569860 最近再ITEYE上看到关于讨论JAVA缓存技术的帖子比较多,自己不懂,所以上网大概搜了下,找到一篇 ...
 
随机推荐
- CSS中盒子模型和position(一)
			
今天遇到几个css中的重要的知识点,记得这些都是以前看过的:margin.padding.border和position.可是用起来还是有很多的问题,以前自己看过去总是懒得记录,等到用起来了都不知道自 ...
 - MySQL高可用读写分离方案预研
			
目前公司有需求做MySQL高可用读写分离,网上搜集了不少方案,都不尽人意,下面是我结合现有组件拼凑的实现方案,亲测已满足要求,希望各位多提建议 :) 一. 网上方案整理(搜集地址不详...) 1 ...
 - KMP算法原理
			
前几天在看数据结构与算法,里面提到过kmp算法,一个超级经典的字符串匹配算法.虽然网上有一大堆关于kmp算法的介绍文章,但是我看过之后还是“不明觉厉”.所以打算自己写写,大家一起学习吧. 一.关于KM ...
 - jQuery设计思想
			
jQuery设计思想 原文网址:http://jqfundamentals.com/book/ 阮一峰 翻译整理 [目录] 一.选择网页元素 二.改变结果集 三.链式操作 四.元素的操作:取值和赋值 ...
 - 运用.NIT将数据存入数据库、读取数据库(运用封装)陈老师作业
			
我基础不好,根据所学的知识,书本的例题修改的,也不知道我理解的是否符合老师要求 运用C#将数据存入数据库.并且可以读取数据库里的数据,此项目我运用了封装.我运用了一个窗体将数据存读数据. 我首先创建了 ...
 - SqlServer Split函数
			
Create FUNCTION [dbo].[SplitToTable] ( @SplitString nvarchar(max), @Separator nvarchar(10)=' ' ) RET ...
 - LAMP环境的搭建
			
[一些前言废话]一名web开发尤其是后端不懂LAMP环境的搭建,那就摊上事了,有些人说他一直用win下的wampServer这种傻瓜式环境搭建,用的挺好的,也有人说他用云服务器,搭配“一键搭建LAMP ...
 - UIFontFamily
			
Family: Hiragino Kaku Gothic ProN W3 Font: HiraKakuProN-W3 Family: Courier Font: Courier ...
 - DSP5509的时钟发生器(翻译总结自TI官方文档)
			
一.C5509时钟发生器的两个功能 1.将从CLKIN引脚输入的时钟信号变换为适当频率的CPU时钟,提供给CPU.外设和其他模块使用: 2.将CPU时钟通过可编程分频器输出到CLKOUT引脚. 时钟发 ...
 - Performance tips
			
HTML5 Techniques for Optimizing Mobile Performance Scrolling Performance layout-performance