ehcache常用API整理
鉴于csdn的blog的不稳定, 及混乱的编辑器, 和无上传功能, 遂决定彻底投诚javaeye的blog.
数月前整理的一个东西, 作为cache的扫盲文档.参考了它的官方文档.
对ehcache感兴趣的兄台可以参考.
附件为eclipse项目, 直接导入, 运行test目录下的junit testcase, 可一目了然.
一 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的注释说明.
- ehcacheTest.rar (1.4 MB)
- 下载次数: 1585
ehcache常用API整理的更多相关文章
- Go语言中使用K8s API及一些常用API整理
Go Client 在进入代码之前,理解k8s的go client项目是对我们又帮助的.它是k8s client中最古老的一个,因此具有很多特性. Client-go 没有使用Swagger生成器,就 ...
- iOS ReactiveCocoa 最全常用API整理(可做为手册查询)
本文适合有一定RAC基础的童鞋做不时的查询,所以本文不做详细解释. 一.常见类 1.RACSiganl 信号类. RACEmptySignal :空信号,用来实现 RACSignal 的 +empty ...
- UI Automator 常用 API 整理
主要类: import android.support.test.uiautomator.UiDevice; 作用:设备封装类,测试过程中获取设备信息和设备交互. import android.sup ...
- 【原创】大数据基础之ElasticSearch(2)常用API整理
Fortunately, Elasticsearch provides a very comprehensive and powerful REST API that you can use to i ...
- hutool工具类常用API整理
0.官网学习地址 https://www.hutool.cn/ 1.依赖 <dependency> <groupId>cn.hutool</groupId> < ...
- seajs常用API整理
本文来自于https://github.com/seajs/seajs/issues/266
- node.js整理 02文件操作-常用API
NodeJS不仅能做网络编程,而且能够操作文件. 拷贝 小文件拷贝 var fs = require('fs'); function copy(src, dst) { fs.writeFileSync ...
- canvas学习之API整理笔记(二)
前面我整理过一篇文章canvas学习之API整理笔记(一),从这篇文章我们已经可以基本了解到常用绘图的API.简单的变换和动画.而本篇文章的主要内容包括高级动画.像素操作.性能优化等知识点,讲解每个知 ...
- js的常用api
JavaScript常用API总结 原创 2016-10-02 story JavaScript 下面是我整理的一些JavaScript常用的API清单. 目录 元素查找 class操作 节点操作 属 ...
随机推荐
- [CentOS7] vncviewer与windows之间的复制粘贴
转载:https://my.oschina.net/seava/blog/226966 用VNC连接到Linux之后,最纠结的问题就是无法复制粘贴.其实很简单,在Linux里面,打开一个终端,然后输入 ...
- 《OD学hadoop》20160910某旅游网项目实战
一.event事件分析 叶子节点只计算一次 父节点的触发次数由子节点的数量节点 事件流:是由业务人员定义的一系列的具有前后顺序的事件构成的用户操作行为,至少包括两个事件以上. 目标:以事件流为单位,分 ...
- bzoj2132: 圈地计划(最小割)
传送门 看来以后见到矩形就要黑白染色冷静一下了…… 首先,如果它的要求时候相邻的选择相同,那么就是和这一题一样了->这里 然后考虑不同的要怎么做 那就把矩形黑白染色一下吧 然后令其中一种颜色的A ...
- bzoj2229: [Zjoi2011]最小割(最小割树)
传送门 这题是用最小割树做的(不明白最小割树是什么的可以去看看这一题->这里) 有了最小割树就很简单了……点数那么少……每次跑出一个最大流就暴力搞一遍就好了 //minamoto #includ ...
- mui 上拉加载更多的使用
最近工作之余在用mui的框架开发,对mui了解了一些.在真正的app开发项目中,mui上拉加载模块中有两个坑,现在说一下. 1.在函数自己上拉加载行为后的回调函数 该函数是必须要写的,用来写自己的逻辑 ...
- FoundToday 隐私政策
FoundToday 隐私政策 本应用尊重并保护所有使用服务用户的个人隐私权.为了给您提供更准确.更有个性化的服务,本应用会按照本隐私权政策的规定使用和披露您的个人信息.但本应用将以高度的勤勉.审慎义 ...
- Windows 在目录中搜索哪个文件中有指定字符串
findstr /s /i "string" *.* 表示,当前目录以及子目录下的所有文件中查找"string"这个字符串. *.*表示所有类型的文件. /s ...
- 未找到与约束 Micorosoft.CodeAnalysis.Editor.TypeScript.ToolsOptions.IUserSettingsProvider
问题: 未找到与约束 ContractName Micorosoft.CodeAnalysis.Editor.TypeScript.ToolsOptions.IUserSettingsProvide ...
- Django---登录(含随机生成图片验证码)、注册示例讲解
登录(验证码).注册功能具体代码 # urls.py from django.contrib import admin from django.urls import path from app01 ...
- Jmeter4.0----CSV Data Set Config_对输入参数进行参数化(14)
1.说明 测试接口时,当请求参数不是固定的,每次请求对应的参数都是不同的,就需要对请求参数进行参数化. 2.步骤 第一步:准备数据 (以报告编制人员为例)首先创建.txt文本,自己编辑要参数化的内容 ...