ehcache 缓存技术

一 ehcache API:

1: Using the CacheManager

1.1所有ehcache的使用, 都是从 CacheManager. 开始的.
有多种方法创建CacheManager实例:

Java代码  

  1. //Create a singleton CacheManager using defaults, then list caches.
  2. CacheManager.getInstance()

或者:

Java代码  

  1. //Create a CacheManager instance using defaults, then list caches.
  2. CacheManager manager = new CacheManager();
  3. String[] cacheNames = manager.getCacheNames();

如果需要从指定配置文件创建 CacheManager:

Java代码  

  1. Create two CacheManagers, each with a different configuration, and list the caches in each.
  2. CacheManager manager1 = new CacheManager("src/config/ehcache1.xml");
  3. CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");
  4. String[] cacheNamesForManager1 = manager1.getCacheNames();
  5. String[] cacheNamesForManager2 = manager2.getCacheNames();

1.2 Adding and Removing Caches Programmatically
手动创建一个cache, 而不是通过配置文件:

Java代码  

  1. //creates a cache called testCache, which
  2. //will be configured using defaultCache from the configuration
  3. CacheManager singletonManager = CacheManager.create();
  4. singletonManager.addCache("testCache");
  5. Cache test = singletonManager.getCache("testCache");

或者:

Java代码  

  1. //Create a Cache and add it to the CacheManager, then use it. Note that Caches are not usable until they have
  2. //been added to a CacheManager.
  3. public void testCreatCacheByProgram()
  4. {
  5. CacheManager singletonManager = CacheManager.create();
  6. Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
  7. singletonManager.addCache(memoryOnlyCache);
  8. Cache testCache = singletonManager.getCache("testCache");
  9. assertNotNull(testCache);
  10. }

手动移除一个cache:

Java代码  

  1. //Remove cache called sampleCache1
  2. CacheManager singletonManager = CacheManager.create();
  3. singletonManager.removeCache("sampleCache1");

1.3 Shutdown the CacheManager
ehcache应该在使用后关闭, 最佳实践是在code中显式调用:

Java代码  

  1. //Shutdown the singleton CacheManager
  2. CacheManager.getInstance().shutdown();

2 Using Caches
比如我有这样一个cache:

Xml代码  

  1. <cache name="sampleCache1" maxElementsInMemory="10000"
  2. maxElementsOnDisk="1000" eternal="false" overflowToDisk="true"
  3. diskSpoolBufferSizeMB="20" timeToIdleSeconds="300"
  4. timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" />

2.1 Obtaining a reference to a Cache
获得该cache的引用:

Java代码  

  1. String cacheName = "sampleCache1";
  2. CacheManager manager = new CacheManager("src/ehcache1.xml");
  3. Cache cache = manager.getCache(cacheName);

2.2 Performing CRUD operations
下面的代码演示了ehcache的增删改查:

Java代码  

  1. public void testCRUD()
  2. {
  3. String cacheName = "sampleCache1";
  4. CacheManager manager = new CacheManager("src/ehcache1.xml");
  5. Cache cache = manager.getCache(cacheName);
  6. //Put an element into a cache
  7. Element element = new Element("key1", "value1");
  8. cache.put(element);
  9. //This updates the entry for "key1"
  10. cache.put(new Element("key1", "value2"));
  11. //Get a Serializable value from an element in a cache with a key of "key1".
  12. element = cache.get("key1");
  13. Serializable value = element.getValue();
  14. //Get a NonSerializable value from an element in a cache with a key of "key1".
  15. element = cache.get("key1");
  16. assertNotNull(element);
  17. Object valueObj = element.getObjectValue();
  18. assertNotNull(valueObj);
  19. //Remove an element from a cache with a key of "key1".
  20. assertNotNull(cache.get("key1"));
  21. cache.remove("key1");
  22. assertNull(cache.get("key1"));
  23. }

2.3    Disk Persistence on demand

Java代码  

  1. //sampleCache1 has a persistent diskStore. We wish to ensure that the data //and index are written immediately.
  2. public void testDiskPersistence()
  3. {
  4. String cacheName = "sampleCache1";
  5. CacheManager manager = new CacheManager("src/ehcache1.xml");
  6. Cache cache = manager.getCache(cacheName);
  7. for (int i = 0; i < 50000; i++)
  8. {
  9. Element element = new Element("key" + i, "myvalue" + i);
  10. cache.put(element);
  11. }
  12. cache.flush();
  13. Log.debug("java.io.tmpdir = " + System.getProperty("java.io.tmpdir"));
  14. }

备注: 持久化到硬盘的路径由虚拟机参数"java.io.tmpdir"决定.
例如, 在windows中, 会在此路径下
C:\Documents and Settings\li\Local Settings\Temp
在linux中, 通常会在: /tmp 下

2.4  Obtaining Cache Sizes
以下代码演示如何获得cache个数:

Java代码  

  1. public void testCachesizes()
  2. {
  3. long count = 5;
  4. String cacheName = "sampleCache1";
  5. CacheManager manager = new CacheManager("src/ehcache1.xml");
  6. Cache cache = manager.getCache(cacheName);
  7. for (int i = 0; i < count; i++)
  8. {
  9. Element element = new Element("key" + i, "myvalue" + i);
  10. cache.put(element);
  11. }
  12. //Get the number of elements currently in the Cache.
  13. int elementsInCache = cache.getSize();
  14. assertTrue(elementsInCache == 5);
  15. //Cache cache = manager.getCache("sampleCache1");
  16. long elementsInMemory = cache.getMemoryStoreSize();
  17. //Get the number of elements currently in the DiskStore.
  18. long elementsInDiskStore = cache.getDiskStoreSize();
  19. assertTrue(elementsInMemory + elementsInDiskStore == count);
  20. }

3: Registering CacheStatistics in an MBeanServer
ehCache 提供jmx支持:

Java代码  

  1. CacheManager manager = new CacheManager();
  2. MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
  3. ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true);

把该程序打包, 然后:

Java代码  

  1. java -Dcom.sun.management.jmxremote -jar 程序名.jar

再到javahome/bin中运行jconsole.exe, 便可监控cache.

4. 用户可以自定义处理cacheEventHandler, 处理诸如元素放入cache的各种事件(放入,移除,过期等事件)
只需三步:
4.1 在cache配置中, 增加cacheEventListenerFactory节点.

Java代码  

  1. <cache name="Test" maxElementsInMemory="1" eternal="false"
  2. overflowToDisk="true" timeToIdleSeconds="1" timeToLiveSeconds="2"
  3. diskPersistent="false" diskExpiryThreadIntervalSeconds="1"
  4. memoryStoreEvictionPolicy="LFU">
  5. <cacheEventListenerFactory class="co.ehcache.EventFactory" />
  6. </cache>

4.2: 编写EventFactory, 继承CacheEventListenerFactory:

Java代码  

  1. public class EventFactory extends CacheEventListenerFactory
  2. {
  3. @Override
  4. public CacheEventListener createCacheEventListener(Properties properties)
  5. {
  6. // TODO Auto-generated method stub
  7. return new CacheEvent();
  8. }
  9. }

4.3  编写 class: CacheEvent, 实现 CacheEventListener 接口:

Java代码  

  1. public class CacheEvent implements CacheEventListener
  2. {
  3. public void dispose()
  4. {
  5. log("in dispose");
  6. }
  7. public void notifyElementEvicted(Ehcache cache, Element element)
  8. {
  9. // TODO Auto-generated method stub
  10. log("in notifyElementEvicted" + element);
  11. }
  12. public void notifyElementExpired(Ehcache cache, Element element)
  13. {
  14. // TODO Auto-generated method stub
  15. log("in notifyElementExpired" + element);
  16. }
  17. public void notifyElementPut(Ehcache cache, Element element) throws CacheException
  18. {
  19. // TODO Auto-generated method stub
  20. log("in notifyElementPut" + element);
  21. }
  22. public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException
  23. {
  24. // TODO Auto-generated method stub
  25. log("in notifyElementRemoved" + element);
  26. }
  27. public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException
  28. {
  29. // TODO Auto-generated method stub
  30. log("in notifyElementUpdated" + element);
  31. }
  32. public void notifyRemoveAll(Ehcache cache)
  33. {
  34. // TODO Auto-generated method stub
  35. log("in notifyRemoveAll");
  36. }
  37. public Object clone() throws CloneNotSupportedException
  38. {
  39. return super.clone();
  40. }
  41. private void log(String s)
  42. {
  43. Log.debug(s);
  44. }
  45. }

现在可以编写测试代码:

Java代码  

  1. public void testEventListener()
  2. {
  3. String key = "person";
  4. Person person = new Person("lcl", 100);
  5. MyCacheManager.getInstance().put("Test", key, person);
  6. Person p = (Person) MyCacheManager.getInstance().get("Test", key);
  7. try
  8. {
  9. Thread.sleep(10000);
  10. }
  11. catch (InterruptedException e)
  12. {
  13. // TODO Auto-generated catch block
  14. e.printStackTrace();
  15. }
  16. assertNull(MyCacheManager.getInstance().get("Test", key));
  17. }

根据配置, 该缓存对象生命期只有2分钟, 在Thread.sleep(10000)期间, 该缓存元素将过期被销毁, 在销毁前, 触发notifyElementExpired事件.
    
二 Ehcache配置文件
 以如下配置为例说明:

Xml代码  

  1. <cache name="CACHE_FUNC"
  2. maxElementsInMemory="2"
  3. eternal="false"
  4. timeToIdleSeconds="10"
  5. timeToLiveSeconds="20"
  6. overflowToDisk="true"
  7. diskPersistent="true"
  8. 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的注释说明.

时间: 2024-08-30 15:48:06

ehcache 缓存技术的相关文章

ehcache缓存技术的特性

Ehcache是现在最流行的纯Java开源缓存框架,配置简单.结构清晰.功能强大,最初知道它,是从hibernate的缓存开始的.网上中文的EhCache材料以简单介绍和配置方法居多,如果你有这方面的问题,请自行google:对于API,官网上介绍已经非常清楚,请参见官网:但是很少见到特性说明和对实现原理的分析,因此在这篇文章里面,我会详细介绍和分析EhCache的特性,加上一些自己的理解和思考,希望对缓存感兴趣的朋友有所收获. 一.特性一览,来自官网,简单翻译一下: 1.快速轻量 过去几年,诸

EHCache页面缓存技术

EHCache的jar包 :http://ehcache.org/downloads/catalog   这里用的是EHcache的web包. 在项目的web.xml文件中加入一个filter: <!--EHCache 页面缓存技术,该页面缓存技术用于page -> filter之间,若是局部页面缓存,           则用SimplePageFragmentCachingFilter,但应注意局部页面要被其他页面 jsp:include     -->     <filter

(转)java缓存技术,记录

http://blog.csdn.net/madun/article/details/8569860 最近再ITEYE上看到关于讨论JAVA缓存技术的帖子比较多,自己不懂,所以上网大概搜了下,找到一篇,暂作保存,后面如果有用到可以参考.此为转贴,帖子来处:http://cogipard.info/articles/cache-static-files-with-jnotify-and-ehcache 介绍 JNotify:http://jnotify.sourceforge.net/,通过JNI

强大的Spring缓存技术(上)

缓存是实际工作中非常常用的一种提高性能的方法, 我们会在许多场景下来使用缓存. 本文通过一个简单的例子进行展开,通过对比我们原来的自定义缓存和 spring 的基于注释的 cache 配置方法,展现了 spring cache 的强大之处,然后介绍了其基本的原理,扩展点和使用场景的限制.通过阅读本文,你应该可以短时间内掌握 spring 带来的强大缓存技术,在很少的配置下即可给既有代码提供缓存能力. 概述 Spring 3.1 引入了激动人心的基于注释(annotation)的缓存(cache)

mybatis0210 mybatis和ehcache缓存框架整合

1.1mybatis和ehcache缓存框架整合 一般不用mybatis来管理缓存而是用其他缓存框架在管理缓存,因为其他缓存框架管理缓存会更加高效,因为别人专业做缓存的而mybatis专业做sql语句的,mybatis二级缓存通过ehcache维护缓存数据. 1.1.1分布缓存 将缓存数据数据进行分布式管理.用户发起请求,首先会根据负载选择不同的服务器,如果用户在服务器1和服务器2都登录过,那么把用户的session分别放在服务器1和服务器2是不行的,所以就把用户的信息放在远程服务器集群中统一管

JAVA缓存技术

最近再ITEYE上看到关于讨论JAVA缓存技术的帖子比较多,自己不懂,所以上网大概搜了下,找到一篇,暂作保存,后面如果有用到可以参考.此为转贴,帖子来处:http://cogipard.info/articles/cache-static-files-with-jnotify-and-ehcache 介绍 JNotify:http://jnotify.sourceforge.net/,通过JNI技术,让Java代码可以实时的监控制定文件夹内文件的变动信息,支持Linux/Windows/MacO

我们究竟什么时候可以使用Ehcache缓存(转)

一.Ehcache是什么 EhCache是Hibernate的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力. 二.Ehcache的使用场景是什么 1.首先最主要就是页面缓存. 网站页面的数据来源非常广泛的,大多数来自不同的对象,而且有可能来自不同的db,所以给页面做缓存是一个不错的主意. 2.常用数据的缓存一些配置信息,如后台的某些不经常改变的设置都可以缓存起来. 三.Ehcache使用的注意点 1.比较少的更新数据表的情况2.

深入探讨在集群环境中使用 EhCache 缓存系统

EhCache 缓存系统简介 EhCache 是一个纯 Java 的进程内缓存框架,具有快速.精干等特点,是 Hibernate 中默认的 CacheProvider. 下图是 EhCache 在应用程序中的位置: 图 1. EhCache 应用架构图 EhCache 的主要特性有: 快速: 简单: 多种缓存策略: 缓存数据有两级:内存和磁盘,因此无需担心容量问题: 缓存数据会在虚拟机重启的过程中写入磁盘: 可以通过 RMI.可插入 API 等方式进行分布式缓存: 具有缓存和缓存管理器的侦听接口

集群环境中使用 EhCache 缓存系统

EhCache 缓存系统 : 本章节将要介绍EhCache及EhCache实现分布式的一些解决方案.并针对于这些解决性方案做一个实现,后续将出一个提供项目模块化.服务化.插件化的VieMall快速开发平台,同时集成Dubbo服务化.Zookeeper(分布式调度/分布式配置管理服务).Redis分布式缓存技术及Memcache/Ehcache 二级缓存切换.FastDFS分布式文件系统.ActiveMQ异步消息中间件.Solr搜索.Nginx负载均衡等分布式及读写分离.如果有时间可以深入分表分库