---
title: "Encache"
author: "teacake"
date: "2009-03-12T23:22:46Z"
tags: []
slug: "encache"
draft: false
lastmod: "2009-03-12T23:22:46Z"
id: 348356
url: "https://teacake.iteye.com/blog/348356"
---

源文档 &lt;[http://wj98127.iteye.com/blog/342397](http://wj98127.iteye.com/blog/342397) &gt;

 

EhCache 一般用途如下： Hibernate 缓存， DAO 缓存，安全性凭证缓存（ Acegi ）， Web 缓存，应用持久化和分布式缓存。

    EhCache 在默认情况下，即在用户未提供自身配置文件ehcache.xml或ehcache-failsafe.xml时，EhCache会依据其自身Jar存档包含的ehcache-failsafe.xml文件所定制的策略来管理缓存。如果用户在classpath下提供了ehcache.xml或ehcache-failsafe.xml文件，那么EhCache将会应用这个文件。如果两个文件同时提供，那么EhCache会使用ehcache.xml文件的配置。 EhCache默认内容如下：

 

&lt; ehcache &gt;

&lt;diskStore   path = "C:\\Acegi6"   /&gt;    

&lt; defaultCache

            maxElementsInMemory = "10000"

            eternal = "false"

            timeToIdleSeconds = "120"

            timeToLiveSeconds = "120"

            overflowToDisk = "true"

            maxElementsOnDisk = "10000000"

            diskPersistent = "false"

            diskExpiryThreadIntervalSeconds = "120"

            memoryStoreEvictionPolicy = "LRU"

             /&gt;

&lt;/ ehcache &gt;

属性说明：

l  diskStore ：指定数据在磁盘中的存储位置。

l  defaultCache ：当借助 CacheManager.add("demoCache") 创建 Cache 时， EhCache 便会采用&lt;defalutCache/&gt;指定的的管理策略

以下属性是必须的：

l  maxElementsInMemory - 在内存中缓存的 element 的最大数目

l  maxElementsOnDisk - 在磁盘上缓存的 element 的最大数目

l  eternal - 设定缓存的 elements 是否永远不过期。如果为 true ，则缓存的数据始终有效，如果为 false 那么还要根据 timeToIdleSeconds ， timeToLiveSeconds 判断

l  overflowToDisk - 设定当内存缓存溢出的时候是否将过期的 element 缓存到磁盘上

以下属性是可选的：

l  timeToIdleSeconds - 当缓存在 EhCache 中的数据前后两次访问的时间超过 timeToIdleSeconds 的属性取值时，这些数据便会删除 .

l  timeToLiveSeconds - 缓存 element 的有效生命期

l  diskPersistent - 在 VM 重启的时候是否启用磁盘保存 EhCache 中的数据，默认是 false 。

l  diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔，默认是 120 秒。每个 120s ，相应的线程会进行一次 EhCache 中数据的清理工作

l  memoryStoreEvictionPolicy - 当内存缓存达到最大，有新的 element 加入的时候，   移除缓存中 element 的策略。默认是 LRU （最近最少使用），可选的有 LFU （最不常使用）和 FIFO （先进先出）

 

 

 

使用简介

 

源文档

[http://www.uusam.com/uu/blog/article/60.htm](http://www.uusam.com/uu/blog/article/60.htm)

1\. cacheNames 列表的取得 ；

    方法一：

        CacheManager.create();

        String\[] cacheNames = CacheManager.getInstance().getCacheNames();

    方法二：

        CacheManager manager = new CacheManager();

        String\[] cacheNames = manager.getCacheNames();

    方法三：

        CacheManager manager1 = new CacheManager("src/config/ehcache1.xml");

        CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");

        String\[] cacheNamesForManager1 = manager1.getCacheNames();

        String\[] cacheNamesForManager2 = manager2.getCacheNames();

2.CacheManager 各种建立的方法：

    方法一：

         CacheManager manager = new CacheManager(); // 实例方式

         CacheManager singletonManager = CacheManager.create(); // 单例方式

 

    方法二：

        CacheManager manager = new CacheManager("src/config/ehcache.xml");

 

    方法三：

        URL url = getClass().getResource("/anotherconfigurationname.xml");

        CacheManager manager = new CacheManager(url);

    方法四：

        InputStream fis = new 

                  FileInputStream(newFile("src/config/ehcache.xml").getAbsolutePath());

        try {

            CacheManager manager = new CacheManager(fis);

        } finally {

            fis.close();

        }

 

 

3\. 添加和删除 Cache

        // 设置一个名为 test 的新 cache,test 属性为默认

        CacheManager singletonManager = CacheManager.create();

        singletonManager.addCache("testCache");

        Cache test = singletonManager.getCache("testCache");

        // 设置一个名为 test 的新 cache, 并定义其属性

        CacheManager singletonManager = CacheManager.create();

        Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);

        manager.addCache (memoryOnlyCache);

        Cache test = singletonManager.getCache("testCache");

        singletonManager.removeCache ("test");

 

 4. 关闭缓存管理器 CacheManager        

        CacheManager.getInstance().shutdown();

  5. 对于缓存对象的 CRUD ：

        // 放入一个简单的对象到缓存元素；

        Cache cache = manager.getCache("sampleCache1");

        Element element = new Element("key1", "value1");

        cache.put (element); //Update

 

       // 得到一个序列化后的对象属性值；

        Cache cache = manager.getCache("sampleCache1");

        Element element = cache.get ("key1"); //query

        Serializable value = element.getValue();

 

        // 得到一个没有序列化后的对象属性值；

        Cache cache = manager.getCache("sampleCache1");

        Element element = cache.get("key1");

        Object value = element.getObjectValue();

 

        // 删除一个对象从元素；

        Cache cache = manager.getCache("sampleCache1");

        Element element = new Element("key1", "value1"

        cache.remove ("key1");

 

      // 对于永固性磁盘存储，立即存储到磁盘：

 

        Cache cache = manager.getCache("sampleCache1");

        cache.flush ();

 

 

6\. 获得缓存大小：

        // 得到缓存的对象数量；

        Cache cache = manager.getCache("sampleCache1");

        int elementsInMemory = cache.getSize();

 

        // 得到缓存对象占用内存的数量

        Cache cache = manager.getCache("sampleCache1");

        long elementsInMemory = cache.getMemoryStoreSize();

 

        // 得到缓存对对象占用磁盘的数量

        Cache cache = manager.getCache("sampleCache1");

        long elementsInMemory = cache.getDiskStoreSize();

 

7\. 关于缓存的读取和丢失的记录

        得到缓存读取的命中次数；

        Cache cache = manager.getCache("sampleCache1");

        int hits = cache.getHitCount();

 

        得到内存中缓存读取的命中次数；

        Cache cache = manager.getCache("sampleCache1");

        int hits = cache.getMemoryStoreHitCount();

 

        得到磁盘中缓存读取的命中次数；

        Cache cache = manager.getCache("sampleCache1");

        int hits = cache.getDiskStoreCount();

 

        得到缓存读取的丢失次数；

        Cache cache = manager.getCache("sampleCache1");

        int hits = cache.getMissCountNotFound();

 

        得到缓存读取的已经被销毁的对象丢失次数；

        Cache cache = manager.getCache("sampleCache1");

        int hits = cache.getMissCountExpired();

 

 

 

 

 

 

 

 

 

[Ehcache页面缓存的使用](http://www.iteye.com/topic/128458)

 

源文档 &lt;[http://www.iteye.com/topic/128458](http://www.iteye.com/topic/128458) &gt;

关于缓存的话题，在坛子里已经有很多讨论，简单的来说，如果一个应用中80% 的时间内都在访问20% 的数据，那么，这时候就应该使用缓存了。这个和长尾理论正好相悖，其实也不是相悖，只是不同的理论使用的场景不同。在80/20 原则生效的地方，我们都应该考虑是否可以使用缓存。但即使是这样，缓存也有不同的用法，举个例子，一个网站的首页估计是被访问的次数最多的，我们可以考虑给首页做一个页面缓存，而如果在某个页面上，比如说javaeye 的java 版区只有前几个页面是访问最频繁的，（假设javaeye 是使用hibernate ，当然这只是假设，我们都知道javaeye 是使用ror 开发的）那么我们就可以考虑给java 版区的record 做二级缓存了，因为二级缓存中是按照对象的id 来保存的，所以应该来说这前面几页使用的对象会一直存在于缓存之中（如何使用hibernate 的二级缓存坛子上也有介绍）。由此可见不同的页面的缓存策略有可能有天壤之别。

本文的目的就是上面所讲的两种情况之一，页面缓存。毫无疑问，几乎所有的网站的首页都是访问率最高的，而首页上的数据来源又是非常广泛的，大多数来自不同的对象，而且有可能来自不同的db ，所以给首页做缓存是一个不错的主意，那么主页的缓存策略是什么样子的呢，我认为应该是某个固定时间之内不变的，比如说2 分钟更新一次。那么这个缓存应该做在什么地方呢，让我们来看一下，假设您的应用的结构是page-filter-action-service-dao-db ，这个过程中的- 的地方都是可以做缓存的地方，根据页面缓存的特征，应该把页面缓存做到尽量靠近客户的地方，就是在page 和filter 之间，这样的优点就是第一个用户请求之后，页面被缓存，第二个用户再来请求的时候，走到filter 这个请求就结束了，无需再走后面的action-service-dao-db 。带来的好处是服务器压力的减低和客户段页面响应速度的加快。

 

那么我们来看一下如何使用ehcache 做到这一点。

 

在使用ehcache 的页面缓存之前，我们必须要了解ehcache 的几个概念，

1 timeToIdleSeconds ，多长时间不访问该缓存，那么ehcache 就会清除该缓存。

2 timeToLiveSeconds ，缓存的存活时间，从开始创建的时间算起。

 

看到这里，我们知道，首页的页面缓存的存活时间，我们定的是2 分钟，那么也就是说我们的timeToLiveSeconds 应该设置为120 ，同时我们的timeToIdleSeconds 最好也设置为2 分钟，或者小于2 分钟。我们来看一下下面这个配置，这个配置片段应该放到ehcache.xml 中：

 

&lt; cache name = "SimplePageCachingFilter"

           maxElementsInMemory = "10"

           maxElementsOnDisk = "10"

           eternal = "false"

            overflowToDisk = "true"

           diskSpoolBufferSizeMB = "20"

           timeToIdleSeconds = "10"

           timeToLiveSeconds = "10"

           memoryStoreEvictionPolicy = "LFU"

            /&gt;

 

SimplePageCachingFilter 是缓存的名字，maxElementsInMemory 表示内存中SimplePageCachingFilter 缓存中元素的最大数量为10 ，maxElementsOnDisk 是指持久化该缓存的元素到硬盘上的最大数量也为10 （），eternal=false 意味着该缓存会死亡。overflowToDisk=true 意思是表示当缓存中元素的数量超过限制时，就把这些元素持久化到硬盘，如果overflowToDisk 是false ，那么maxElementsOnDisk 的设置就没有什么意义了。memoryStoreEvictionPolicy=LFU 是指按照缓存的hit 值来清除，也就是说缓存满了之后，新的对象需要缓存时，将会将缓存中hit 值最小的对象清除出缓存，给新的对象腾出地方来了（文章最后有ehcache 中自带的3 种缓存清空策略的介绍）。

 

接着我们来看一下SimplePageCachingFilter 的配置，

&lt; filter &gt;

        &lt; filter-name &gt; indexCacheFilter filter-name &gt;

        &lt; filter-class &gt;

            net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter

        filter-class &gt;

filter &gt;

 

    &lt; filter-mapping &gt;

        &lt; filter-name &gt; indexCacheFilter filter-name &gt;

        &lt; url-pattern &gt; \*index.action url-pattern &gt;

filter-mapping &gt;

就只需要这么多步骤，我们就可以给某个页面做一个缓存的，把上面这段配置放到你的web.xml 中，那么当你打开首页的时候，你会发现，2 分钟才会有一堆sql 语句出现在控制台上。当然你也可以调成5 分钟，总之一切都在控制中。

 

好了，缓存整个页面看上去是非常的简单，甚至都不需要写一行代码，只需要几行配置就行了，够简单吧，虽然看上去简单，但是事实上内部实现却不简单哦，有兴趣的话，大家可以看看SimplePageCachingFilter 继承体系的源代码。

 

上面的配置针对的情况是缓存首页的全部，如果你只想缓存首页的部分内容时，你需要使用SimplePageFragmentCachingFilter 这个filter 。我们看一下如下片断：

 

&lt; filter &gt;

        &lt; filter-name &gt; indexCacheFilter filter-name &gt;

        &lt; filter-class &gt;

            net.sf.ehcache.constructs.web.filter.SimplePageFragmentCachingFilter

        filter-class &gt;

filter &gt;

 

    &lt; filter-mapping &gt;

        &lt; filter-name &gt; indexCacheFilter filter-name &gt;

        &lt; url-pattern &gt; \*/index\_right.jsp url-pattern &gt;

filter-mapping &gt;

 

这个jsp 需要被jsp:include 到其他页面，这样就做到的局部页面的缓存。这一点貌似没有oscache 的tag 好用。

 

事实上在cachefilter 中还有一个特性，就是gzip ，也就是说缓存中的元素是被压缩过的，如果客户浏览器支持压缩的话，filter 会直接返回压缩过的流，这样节省了带宽，把解压的工作交给了客户浏览器，如果客户的浏览器不支持gzip ，那么filter 会把缓存的元素拿出来解压后再返回给客户浏览器（大多数爬虫是不支持gzip 的，所以filter 也会解压后再返回流），这样做的优点是节省带宽，缺点就是增加了客户浏览器的负担（但是我觉得对当代的计算机而言，这个负担微乎其微）。

 

好了，如果你的页面正好也需要用到页面缓存，不防可以考虑一下ehcache ，因为它实在是非常简单，而且易用。

 

总结：ehcache 是一个非常轻量级的缓存实现，而且从1.2 之后就支持了集群，目前的最新版本是1.3 ，而且是hibernate 默认的缓存provider 。虽然本文是介绍的是ehcache 对页面缓存的支持，但是ehcache 的功能远不止如此，当然要使用好缓存，对JEE 中缓存的原理，使用范围，适用场景等等都需要有比较深刻的理解，这样才能用好缓存，用对缓存。

 

最后复习一下ehcache 中缓存的3 种清空策略：

1 FIFO ，first in first out ，这个是大家最熟的，先进先出，不多讲了

2 LFU ， Less Frequently Used ，就是上面例子中使用的策略，直白一点就是讲一直以来最少被使用的。如上面所讲，缓存的元素有一个hit 属性，hit 值最小的将会被清出缓存。

2 LRU ，Least Recently Used ，最近最少使用的，缓存的元素有一个时间戳，当缓存容量满了，而又需要腾出地方来缓存新的元素的时候，那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。

 

 

 

 [Ehcache集群环境配置](http://www.iteye.com/topic/335623)

- 1. &lt;cacheManagerPeerProviderFactory  class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
  2. properties="peerDiscovery=manual,rmiUrls=//192.168.2.23:40001/userCache|//192.168.2.23:40001/resourceCache"  /&gt;
  
  <!--THE END-->
  
  1. &lt;cacheManagerPeerListenerFactory  class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
  2. properties="hostName=192.168.2.154,  port=40001,socketTimeoutMillis=2000" /&gt;
  
  <!--THE END-->
  
  1. &lt;cache  name="userCache" maxElementsInMemory="10000" eternal="true" overflowToDisk="true" timeToIdleSeconds="0" timeToLiveSeconds="0" diskPersistent="false" diskExpiryThreadIntervalSeconds="120"&gt;
  2. &lt;cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"     properties="replicateAsynchronously=true, replicatePuts=true, replicateUpdates=true,replicateUpdatesViaCopy= false, replicateRemovals= true " /&gt;
  3. &lt;/cache&gt;
  
  <!--THE END-->
  
  1. &lt;cacheManagerPeerProviderFactory  class="net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory"
  2. properties="connect=TCP(start\_port=7800):
  3. TCPPING(initial\_hosts=192.168.2.154\[7800],192.168.2.23\[7800];port\_range=10;timeout=3000;
  4. num\_initial\_members=3;up\_thread=true;down\_thread=true):
  5. VERIFY\_SUSPECT(timeout=1500;down\_thread=false;up\_thread=false):
  6. pbcast.NAKACK(down\_thread=true;up\_thread=true;gc\_lag=100;retransmit\_timeout=3000):
  7. pbcast.GMS(join\_timeout=5000;join\_retry\_timeout=2000;shun=false;
  8. print\_local\_addr=false;down\_thread=true;up\_thread=true)"
  9. propertySeparator="::" /&gt;
  
  <!--THE END-->
  
  1. &lt;cache  name="userCache" maxElementsInMemory="10000" eternal="true"
  2. overflowToDisk="true" timeToIdleSeconds="0" timeToLiveSeconds="0"
  3. diskPersistent="false" diskExpiryThreadIntervalSeconds="120"&gt;
  4. &lt;cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
  5. properties="replicateAsynchronously=true, replicatePuts=true,
  6. replicateUpdates=true, replicateUpdatesViaCopy=false, replicateRemovals=true"/&gt;
  7. &lt;/cache&gt;
  
  <!--THE END-->
  
  01. &lt;?xml  version="1.0" encoding="UTF-8"?&gt;
  02. &lt;ehcache  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  03. xsi:noNamespaceSchemaLocation="http://ehcache.sf.net/ehcache.xsd"&gt;
  04. &lt;diskStore path="java.io.tmpdir" /&gt;
  05. &lt;cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory"
  06. properties="connect=TCP(start\_port=7800):
  07. TCPPING(initial\_hosts=192.168.2.154\[7800],192.168.2.23\[7800];port\_range=10;timeout=3000;
  08. num\_initial\_members=3;up\_thread=true;down\_thread=true):
  09. VERIFY\_SUSPECT(timeout=1500;down\_thread=false;up\_thread=false):
  10. pbcast.NAKACK(down\_thread=true;up\_thread=true;gc\_lag=100;retransmit\_timeout=3000):
  11. pbcast.GMS(join\_timeout=5000;join\_retry\_timeout=2000;shun=false;
  12. print\_local\_addr=false;down\_thread=true;up\_thread=true)"
  13. propertySeparator="::" /&gt;
  14. &lt;defaultCache maxElementsInMemory="10000" eternal="true"
  15. overflowToDisk="true" timeToIdleSeconds="0" timeToLiveSeconds="0"
  16. diskPersistent="false" diskExpiryThreadIntervalSeconds="120"&gt;
  17. &lt;cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
  18. properties="replicateAsynchronously=true, replicatePuts=true,
  19. replicateUpdates=true, replicateUpdatesViaCopy=false, replicateRemovals=true"/&gt;
  20. &lt;/defaultCache&gt;
  21. &lt;cache name="velcroCache" maxElementsInMemory="10000" eternal="true"
  22. overflowToDisk="true" timeToIdleSeconds="0" timeToLiveSeconds="0"
  23. diskPersistent="false" diskExpiryThreadIntervalSeconds="120"&gt;
  24. &lt;cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
  25. properties="replicateAsynchronously=true, replicatePuts=true,
  26. replicateUpdates=true, replicateUpdatesViaCopy=false, replicateRemovals=true"/&gt;
  27. &lt;/cache&gt;
  28. &lt;cache name="userCache" maxElementsInMemory="10000" eternal="true"
  29. overflowToDisk="true" timeToIdleSeconds="0" timeToLiveSeconds="0"
  30. diskPersistent="false" diskExpiryThreadIntervalSeconds="120"&gt;
  31. &lt;cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
  32. properties="replicateAsynchronously=true, replicatePuts=true,
  33. replicateUpdates=true, replicateUpdatesViaCopy=false, replicateRemovals=true"/&gt;
  34. &lt;/cache&gt;
  35. &lt;cache name="resourceCache" maxElementsInMemory="10000"
  36. eternal="true" overflowToDisk="true" timeToIdleSeconds="0"
  37. timeToLiveSeconds="0" diskPersistent="false"
  38. diskExpiryThreadIntervalSeconds="120"&gt;
  39. &lt;cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
  40. properties="replicateAsynchronously=true, replicatePuts=true,
  41. replicateUpdates=true, replicateUpdatesViaCopy=false, replicateRemovals=true"/&gt;
  42. &lt;/cache&gt;
  43. &lt;/ehcache&gt;
  
   
  
  源文档 &lt;[http://www.iteye.com/topic/335623](http://www.iteye.com/topic/335623) &gt;
  
   
  
  Ehcache支持的分布式缓存支持有三种RMI，JGroups，JMS，这里介绍下MRI和JGrpups两种方式，Ehcache使用版本为 1.5.0，关于ehcache的其他信息请参考[http://ehcache.sourceforge.net](http://ehcache.sourceforge.net/) /EhcacheUserGuide.html，关于jgroups的信息请参考[http://www.jgroups.org/manual](http://www.jgroups.org/manual) /html\_single/index.html。
  
   
  
  环境为两台机器 server1 ip：192.168.2.154，server2 ip：192.168.2.23
  
   
  
  1\. RMI方式：
  
  rmi的方式配置要点（下面均是server1上的配置，server2上的只需要把ip兑换即可）
  
   
  
  a. 配置PeerProvider：
  
   
  
  Xml代码
  
   
  
  配置中通过手动方式同步sever2中的userCache和resourceCache。
  
   
  
  b. 配置CacheManagerPeerListener：
  
   
  
  Xml代码
  
   
  
    配置中 server1 监听本机 40001 端口。
  
   
  
  c. 在每一个cache中添加cacheEventListener，例子如下：
  
   
  
  Xml代码
  
     
  
  2\. JGroups方式：
  
  ehcache 1.5.0之后版本支持的一种方式，配置起来比较简单，要点：
  
   
  
  a. 配置PeerProvider，使用tcp的方式，例子如下：
  
   
  
  Xml代码
  
   
  
   b. 为每个 cache 添加 cacheEventListener ：
  
   
  
  Xml代码
  
   
  
   JGroup 方式配置的两个 server 上的配置文件一样，若有多个 server ，在 initial\_hosts 中将 server ip 加上即可。
  
  一个完整的ehcache.xml文件：
  
  Xml代码