ehcache是一个纯Java进程内缓存框架,是hibernate默认的Cacheprovider。(出自百度百科)。

1. 快速2. 简单3. 多种缓存策略4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题5. 缓存数据会在虚拟机重启的过程中写入磁盘6. 可以通过RMI、可插入API等方式进行分布式缓存7. 具有缓存和缓存管理器的侦听接口8. 支持多缓存管理器实例,以及一个实例的多个缓存区域9. 提供Hibernate的缓存实现

⑴、简单代码实现:

配置文件2个ehcache.xml 、ehcache.xsd

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:noNamespaceSchemaLocation="ehcache.xsd"
  4. updateCheck="true" monitoring="autodetect"
  5. dynamicConfig="true">
  6. <diskStore path="d:/file"/>
  7. <cache name="ehcache1"
  8. maxElementsInMemory="100"
  9. maxElementsOnDisk="0"
  10. eternal="false"
  11. timeToIdleSeconds="300000"
  12. timeToLiveSeconds="300000"
  13. diskPersistent="true"
  14. overflowToDisk="true"
  15. />
  16.  
  17. </ehcache>

demo调用:

这种调用方式若属性配置了虚拟机重启缓存数据将会报错:

  1. package com.jws.app.junt;
  2.  
  3. import net.sf.ehcache.Cache;
  4. import net.sf.ehcache.CacheManager;
  5. import net.sf.ehcache.Element;
  6. /**
  7. * ehcache框架测试
  8. * @author Administrator
  9. *
  10. */
  11. public class ehcacheDemo {
  12. public static void main(String[] args) {
  13. //CacheManager manager1 = CacheManager.newInstance("src/config/ehcache1.xml");
  14. CacheManager manager = CacheManager.create();
  15. Cache cache = manager.getCache("ehcache1");
  16. // manager.addCache("ehcache2");
  17. //Cache test = manager.getCache("ehcache2");
  18. cache.put(new Element("key1", "values1"));
  19. cache.put(new Element("key2", "values2"));
  20. cache.put(new Element("key3", "values3"));
  21. Element element = cache.get("key1");
  22. System.out.println(element.getValue());
  23. cache.flush();
  24. }
  25.  
  26. }

    配置文件详解:

maxElementsInMemory:    内存中允许缓存的最大数量,若超过这个数量,数据将缓存在磁盘。

maxElementsOnDisk:   硬盘中缓存的最大数量,0表示无限大。

    eternal: 对象是否永久有效,一但设置了,timeout将不起作用。

    timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。

    timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。

    overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。

    diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。

    maxElementsOnDisk:硬盘最大缓存个数。

    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:内存数量最大时是否清除。

    

以下属性是可选的:
timeToIdleSeconds: 对象空闲时间,指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问。
timeToLiveSeconds: 对象存活时间,指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问。
diskPersistent: 是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false。
diskExpiryThreadIntervalSeconds: 对象检测线程运行时间间隔。标识对象状态的线程多长时间运行一次。
diskSpoolBufferSizeMB: DiskStore使用的磁盘大小,默认值30MB。每个cache使用各自的DiskStore。
memoryStoreEvictionPolicy:
如果内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU,可选FIFO、LFU。
 
缓存的3 种清空策略
FIFO ,first in first out (先进先出).
LFU , Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存。
LRU ,Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:noNamespaceSchemaLocation="http://ehcache.sf.net/ehcache.xsd">
  4.  
  5. <diskStore path="d:/file" />
  6.  
  7. <defaultCache
  8. maxElementsInMemory="10000"
  9. eternal="false"
  10. overflowToDisk="true"
  11. timeToIdleSeconds="10"
  12. timeToLiveSeconds="20"
  13. diskPersistent="false" />
  14.  
  15. <cache name="requestCache"
  16. maxElementsInMemory="100000"
  17. eternal="false"
  18. overflowToDisk="false"
  19. timeToIdleSeconds="180"
  20. timeToLiveSeconds="180"
  21. diskPersistent="false"
  22. memoryStoreEvictionPolicy="LFU" />
  23.  
  24. <cache name="myCache"
  25. maxElementsInMemory="2"
  26. eternal="false"
  27. overflowToDisk="true"
  28. timeToIdleSeconds="180"
  29. timeToLiveSeconds="180"
  30. maxElementsOnDisk="0"
  31. diskPersistent="true"
  32. memoryStoreEvictionPolicy="LFU" />
  33. </ehcache>
  1. package com.jws.app.junt;
  2.  
  3. import java.util.List;
  4.  
  5. import net.sf.ehcache.Cache;
  6. import net.sf.ehcache.CacheManager;
  7. import net.sf.ehcache.Element;
  8. /**
  9. * ehcache框架测试
  10. * @author Administrator
  11. *
  12. */
  13. public class ehcacheDemo {
  14. public static void main(String[] args) {
  15. // 指定ehcache.xml的位置
  16. String fileName = "src/main/resources/ehcache.xml";
  17. CacheManager manager = new CacheManager(fileName);
  18. // 取出所有的cacheName
  19. Cache cache = manager.getCache("myCache");
  20. System.out.println(cache.getSize());
  21. //获取单个节点
  22. Element el = cache.get("key1812");
  23. System.out.println("【单个节点】"+el.getValue());
  24. el = cache.get(1);
  25. //System.out.println("【单个节点2】"+el.getValue());
  26. List<Element> cl = cache.getKeys();
  27. // cl.size();
  28.  
  29. //
  30. // for(int i=0;i<1000;i++){
  31. // cache.put(new Element("key1"+ i , "values1"+i));
  32. // }
  33. //
  34.  
  35. // cache.flush();
  36.  
  37. manager.shutdown();
  38. }
  39. }
  1. package com.jws.common.util;
  2.  
  3. import java.util.List;
  4.  
  5. import net.sf.ehcache.Cache;
  6. import net.sf.ehcache.CacheManager;
  7. import net.sf.ehcache.Element;
  8.  
  9. /**
  10. * EHcache工具类 
  11. * @author Administrator
  12. *
  13. */
  14. public class EHCacheConfig {
  15.  
  16. /**
  17. * 当前采用的缓存对象
  18. */
  19. public static String cacheObject = "myCache";
  20. private static CacheManager cacheManager = null;
  21. private static Cache cache = null;
  22.  
  23. static{
  24. EHCacheConfig.initCacheManager();
  25. EHCacheConfig.initCache();
  26. }
  27.  
  28. /**
  29. *
  30. * 初始化缓存管理容器
  31. */
  32. public static CacheManager initCacheManager() {
  33. try {
  34. if (cacheManager == null)
  35. System.out.println("【EHcache start............】");
  36. cacheManager = CacheManager.getInstance();
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. }
  40. return cacheManager;
  41. }
  42.  
  43. /**
  44. * 初始化cache
  45. * @return
  46. */
  47. public static Cache initCache() {
  48. if(cache ==null){
  49. cache = cacheManager.getCache("myCache");
  50. System.out.println("【EHcache cache start............】");
  51. }
  52. return cache;
  53. }
  54. /**
  55. *
  56. * 添加缓存
  57. *
  58. * @param key
  59. * 关键字
  60. * @param value
  61. * 值
  62. */
  63. public static void put(Object key, Object value) {
  64. // 创建Element,然后放入Cache对象中
  65. Element element = new Element(key, value);
  66. cache.put(element);
  67. }
  68.  
  69. /**
  70. * 获取cache
  71. *
  72. * @param key
  73. * 关键字
  74. * @return
  75. */
  76. public static Object get(Object key) {
  77. Element element = cache.get(key);
  78. if (null == element) {
  79. return null;
  80. }
  81. return element.getObjectValue();
  82. }
  83. /**
  84. * 移除所有cache
  85. */
  86.  
  87. /**
  88. * 释放CacheManage
  89. */
  90.  
  91. public static void shutdown() {
  92. cacheManager.shutdown();
  93. }
  94.  
  95. public static void removeAllCache() {
  96. cacheManager.removalAll();
  97. }
  98. /**
  99. *
  100. * 移除所有Element
  101. */
  102. public static void removeAllKey() {
  103. cache.removeAll();
  104. }
  105. /**
  106. *
  107. * 获取所有的cache名称
  108. * @return
  109. */
  110. public static String[] getAllCaches() {
  111. return cacheManager.getCacheNames();
  112. }
  113. /**
  114. *
  115. * 获取Cache所有的Keys
  116. * @return
  117. */
  118. public static List<Element> getKeys() {
  119. return cache.getKeys();
  120. }
  121.  
  122. }

【Java】:ehcache的更多相关文章

  1. 【Java】:压缩成多个压缩卷

    Java自带的库不支持压缩成多个压缩卷,找到了一个开源库 zip4j ,发现更好用 so easy package com.jws.common.mail; import java.io.File; ...

  2. 【Java】:googleSearch

    google custom search是一个基于google的搜索引擎api,可以请求谷歌的搜索数据 pala pala  pala  ... 实现: 1.注册谷歌账号 2.创建google项目 1 ...

  3. 【java】:通用小知识

    1.将String字符串放在最前面 为了防止偶发性的NullPointerException 异常,我们通常将String放置在equals()函数的左边来实现字符串比较,如下代码: // Bad i ...

  4. 【java】:解析xml

    ==========================================xml文件<?xml version="1.0" encoding="GB231 ...

  5. 【java】: 操作excel2007/2003

    //上传位置(与操作excel无关,可不看) public String getUploadPath() { File theWebFolder = XMPPServer.getInstance(). ...

  6. 【java】:生成excel

    //生成报表公用方法 //excelName: 生成的文件名 //list:时间/日期/描述 //listSelectFiled:  标题 //showContent :  文件内容bean //生成 ...

  7. 【java】:常用工具类

    PS; 平时用到的一些工具类,验证非空.字符切割.时间转换.金额转换 package com.jws.common.util; import java.io.UnsupportedEncodingEx ...

  8. 【java】:读取文件

    PS:转 1.按字节读取文件内容2.按字符读取文件内容3.按行读取文件内容4.随机读取文件内容 public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制 ...

  9. 【java】:定时任务

    PS:转 http://blog.csdn.net/lotusyangjun/article/details/6450421/

随机推荐

  1. etcd命令说明 etcd Version: 3.0.15

    etcd Version: 3.0.15Git SHA: fc00305Go Version: go1.6.3Go OS/Arch: linux/amd64 https://github.com/co ...

  2. JavaScript编程总结

    1.   JS加载放在底部 2.   JS和CSS合并,一个页面加载的JS和CSS越少越好 3.   尽量使用变量,页非全局变量. 4.   脚本和DOM交互越少越好,尽量批量修改. 5.   批量修 ...

  3. mysql计算时间差函数

    MySql计算两个日期的时间差函数TIMESTAMPDIFF用法,只要用一句SQL语句就可以办到了. MySql计算两个日期的时间差函数TIMESTAMPDIFF用法: 语法: TIMESTAMPDI ...

  4. VC++中StretchBlt图像失真问题的解决办法

    在 VC 中使用 StretchBlt 会碰到一些与点阵图大小缩放相关的一些问题.在扩展一个点阵图时,StretchBlt必须复制图素行或列.如果放大倍数不是原图的整数倍,那么此操作会造成产生的图像有 ...

  5. Nvelocity用法

    NVelocity用法 NVelocity是一个基于.NET的模板引擎(template engine).它允许任何人仅仅简单的使用模板语言(template language)来引用由.NET代码定 ...

  6. WCF服务二:创建一个简单的WCF服务程序

    在本例中,我们将实现一个简单的计算服务,提供基本的加.减.乘.除运算,通过客户端和服务端运行在同一台机器上的不同进程实现. 一.新建WCF服务 1.新建一个空白解决方案,解决方案名称为"WC ...

  7. linux开机随笔

    (1),linux开机流程: 固件是在软件与硬件之间的那部分,他们既不叫做硬件也不叫做软件, 开机自检  ,就是  在你按下开机键时,电脑就会自动检查你的硬盘  内存 cpu等器件, 那个CMOS是固 ...

  8. matlab计算差分函数diff

    A = 3 2 5 6 5 2 1 8 4 2 7 9 >> diff(A,1,1) ans = 2 0 -4 2 -1 0 6 1 >> diff(A,1,2) ans = ...

  9. 树莓派 config.txt

    树莓派开机默认配置文件:/boot/config.txt # For more options and information see # http://www.raspberrypi.org/doc ...

  10. SQL中EXISTS怎么用[转]

    SQL中EXISTS怎么用 1 2 3 4 分步阅读 EXISTS用于检查子查询是否至少会返回一行数据,该子查询实际上并不返回任何数据,而是返回值True或False 方法/步骤 1 EXISTS用于 ...