EhCache之初试

来源:互联网 发布:24周胎儿发育标准数据 编辑:程序博客网 时间:2024/04/30 16:56
 

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

 

详情参见其官网站:http://ehcache.org/  

具体文件下载网站:http://sourceforge.net/projects/ehcache/files/

 

下面将用实际的Demo分类演示介绍EhCache的初步使用:

  • 单例CacheManager 创建
  • 多个CacheManager 创建
  • Cache的多种创建方式
  • 对Cache的CRUD的操作
  • Cache的统计信息
  • 测试所用两个的ehcache.xml文件

[一]、单例CacheManager 创建

      1.代码示例:

Java代码 复制代码
  1. /**  
  2.     * @blog http://sjsky.iteye.com <br>  
  3.     *       单例CacheManager 创建  
  4.     */  
  5.    public static void testCreateSingleton() {   
  6.        // Create a singleton CacheManager using defaults  
  7.        System.out.println("Create a singleton CacheManager using defaults");   
  8.        // CacheManager.create();   
  9.        System.out.println("CacheManager.create()     :="  
  10.                + CacheManager.getInstance());   
  11.        System.out.println("cacheNames length := "  
  12.                + CacheManager.getInstance().getCacheNames().length);   
  13.        CacheManager.getInstance().shutdown();   
  14.   
  15.        System.out.println("=======================================");   
  16.   
  17.        // Create a singleton CacheManager using a configuration file  
  18.        System.out   
  19.                .println("Create a singleton CacheManager using a configuration file");   
  20.        CacheManager singletonManager2 = CacheManager   
  21.                .create("src/main/java/michael/hibernate/cache/ehcache/ehcache.xml");   
  22.        System.out.println("CacheManager.create(file) :=" + singletonManager2);   
  23.        System.out.println("cacheNames length := "  
  24.                + singletonManager2.getCacheNames().length);   
  25.        System.out   
  26.                .println("CacheManager.getInstance() == singletonManager2 :: "  
  27.                        + (CacheManager.getInstance() == singletonManager2));   
  28.        singletonManager2.shutdown();   
  29.        // CacheManager.getInstance().shutdown();  
  30.   
  31.        System.out.println("=======================================");   
  32.   
  33.        // Create a singleton CacheManager from a configuration resource in the  
  34.        // classpath.   
  35.        URL configurl = Thread.currentThread().getContextClassLoader()   
  36.                .getResource("michael/hibernate/cache/ehcache/ehcache.xml");   
  37.        CacheManager singletonManager3 = CacheManager.create(configurl);   
  38.        System.out.println("CacheManager.create(url)  :=" + singletonManager3);   
  39.   
  40.        String[] cacheNames = singletonManager3.getCacheNames();   
  41.        System.out.println("cacheNames length := " + cacheNames.length);   
  42.        for (String name : cacheNames) {   
  43.            System.out.println("name := " + name);   
  44.        }   
  45.        singletonManager3.shutdown();   
  46.        // CacheManager.getInstance().shutdown();  
  47.    }  
 

      2.运行结果:

Create a singleton CacheManager using defaults
CacheManager.create() :=net.sf.ehcache.CacheManager@e80842
cacheNames length := 4
=======================================
Create a singleton CacheManager using a configuration file
CacheManager.create(file) :=net.sf.ehcache.CacheManager@1bbf1ca
cacheNames length := 6
CacheManager.getInstance() == singletonManager2 :: true
=======================================
CacheManager.create(url) :=net.sf.ehcache.CacheManager@f9c40
cacheNames length := 6
name := sampleRepicatedCache2
name := sampleReplicatedCache1
name := sampleCache2
name := sampleCache1
name := sampleReplicatedCache3
name := sampleCache3

 

[二]、多个CacheManager 创建

      1.代码示例:

Java代码 复制代码
  1. /**  
  2.      * @blog http://sjsky.iteye.com <br>  
  3.      *       CacheManager 创建  
  4.      */  
  5.     public static void testCreateManager() {   
  6.   
  7.         // Create a CacheManager instance using defaults  
  8.         CacheManager manager1 = new CacheManager();   
  9.         System.out.println("new CacheManager()     := " + manager1);   
  10.         String[] cacheNames = manager1.getCacheNames();   
  11.         System.out.println("cacheNames length := " + cacheNames.length);   
  12.         for (String name : cacheNames) {   
  13.             System.out.println("name := " + name);   
  14.         }   
  15.         manager1.shutdown();   
  16.   
  17.         System.out.println("=======================================");   
  18.   
  19.         // Create a CacheManager instance using a configuration file  
  20.         CacheManager manager2 = new CacheManager(   
  21.                 "src/main/java/michael/hibernate/cache/ehcache/ehcache.xml");   
  22.         System.out.println("new CacheManager(file) := " + manager2);   
  23.         System.out.println("cacheNames length := "  
  24.                 + manager2.getCacheNames().length);   
  25.         manager2.shutdown();   
  26.   
  27.         System.out.println("=======================================");   
  28.         // Create a singleton CacheManager from a configuration resource in the  
  29.         // classpath.   
  30.         URL configurl = Thread.currentThread().getContextClassLoader()   
  31.                 .getResource("michael/hibernate/cache/ehcache/ehcache.xml");   
  32.         CacheManager manager3 = new CacheManager(configurl);   
  33.         System.out.println("new CacheManager(url)  := " + manager3);   
  34.         System.out.println("cacheNames length := "  
  35.                 + manager3.getCacheNames().length);   
  36.         for (String name : manager3.getCacheNames()) {   
  37.             System.out.println("name := " + name);   
  38.         }   
  39.         manager3.shutdown();   
  40.   
  41.     }  
 

      2.运行结果:

new CacheManager() := net.sf.ehcache.CacheManager@17653ae
cacheNames length := 4
name := sampleCache2
name := org.hibernate.cache.UpdateTimestampsCache
name := sampleCache1
name := org.hibernate.cache.StandardQueryCache
=======================================
new CacheManager(file) := net.sf.ehcache.CacheManager@1ff0dde
cacheNames length := 6
=======================================
new CacheManager(url) := net.sf.ehcache.CacheManager@db4fa2
cacheNames length := 6
name := sampleRepicatedCache2
name := sampleReplicatedCache1
name := sampleCache2
name := sampleCache1
name := sampleReplicatedCache3
name := sampleCache3
 

[三]、Cache的多种创建方式

      1.代码示例: 

Java代码 复制代码
  1. /**  
  2.  * @blog http://sjsky.iteye.com <br>  
  3.  *       Create Cache  
  4.  */  
  5. public static void testCreateCache() {   
  6.   
  7.     System.out.println("add cache with defaults:");   
  8.     CacheManager singletonManager = CacheManager.create();   
  9.     singletonManager.addCache("myCache1");   
  10.     Cache myCache1 = singletonManager.getCache("myCache1");   
  11.     System.out.println(myCache1);   
  12.   
  13.     System.out.println("add cache with new Cache(arg1,arg2...):");   
  14.     Cache myMemoryCache = new Cache("myMemoryCache"5000falsefalse5,   
  15.             2);   
  16.     singletonManager.addCache(myMemoryCache);   
  17.     System.out.println(singletonManager.getCache("myMemoryCache"));   
  18.   
  19.     System.out.println("Create a Cache specifying its configuration:");   
  20.     // Create a Cache specifying its configuration.  
  21.     int maxElements = 100;   
  22.     Cache myConfigCahce = new Cache(new CacheConfiguration("myConifgCahce",   
  23.             maxElements).memoryStoreEvictionPolicy(   
  24.             MemoryStoreEvictionPolicy.LFU).overflowToDisk(true).eternal(   
  25.             false).timeToLiveSeconds(60).timeToIdleSeconds(30)   
  26.             .diskPersistent(false).diskExpiryThreadIntervalSeconds(0));   
  27.     singletonManager.addCache(myConfigCahce);   
  28.     System.out.println(singletonManager.getCache("myConifgCahce"));   
  29.   
  30.     singletonManager.shutdown();   
  31.   
  32. }  
 

      2.运行结果:

add cache with defaults:
[ name = myCache1 status = STATUS_ALIVE eternal = false overflowToDisk = true maxElementsInMemory = 100 maxElementsOnDisk = 100 memoryStoreEvictionPolicy = LRU timeToLiveSeconds = 120 timeToIdleSeconds = 120 diskPersistent = false diskExpiryThreadIntervalSeconds = 120 cacheEventListeners: net.sf.ehcache.statistics.LiveCacheStatisticsWrapper hitCount = 0 memoryStoreHitCount = 0 diskStoreHitCount = 0 missCountNotFound = 0 missCountExpired = 0 overflowToOffHeap = false maxMemoryOffHeap = null ]
add cache with new Cache(arg1,arg2...):
[ name = myMemoryCache status = STATUS_ALIVE eternal = false overflowToDisk = false maxElementsInMemory = 5000 maxElementsOnDisk = 0 memoryStoreEvictionPolicy = LRU timeToLiveSeconds = 5 timeToIdleSeconds = 2 diskPersistent = false diskExpiryThreadIntervalSeconds = 120 cacheEventListeners: net.sf.ehcache.statistics.LiveCacheStatisticsWrapper hitCount = 0 memoryStoreHitCount = 0 diskStoreHitCount = 0 missCountNotFound = 0 missCountExpired = 0 overflowToOffHeap = false maxMemoryOffHeap = null ]
Create a Cache specifying its configuration:
[ name = myConifgCahce status = STATUS_ALIVE eternal = false overflowToDisk = true maxElementsInMemory = 100 maxElementsOnDisk = 0 memoryStoreEvictionPolicy = LFU timeToLiveSeconds = 60 timeToIdleSeconds = 30 diskPersistent = false diskExpiryThreadIntervalSeconds = 120 cacheEventListeners: net.sf.ehcache.statistics.LiveCacheStatisticsWrapper hitCount = 0 memoryStoreHitCount = 0 diskStoreHitCount = 0 missCountNotFound = 0 missCountExpired = 0 overflowToOffHeap = false maxMemoryOffHeap = null ]
 

 

[四]、对Cache的CRUD的操作

      1.代码示例:

Java代码 复制代码
  1. /**  
  2.   * @blog http://sjsky.iteye.com <br>  
  3.   *       CRUD operations  
  4.   */  
  5.  public static void testCacheElementCRUD() {   
  6.      CacheManager manager = null;   
  7.      try {   
  8.          manager = new CacheManager();   
  9.          manager.addCache("MichaelInfo");   
  10.   
  11.          Cache myCache = manager.getCache("MichaelInfo");   
  12.          System.out.println("manager.getCache :" + myCache);   
  13.   
  14.          Element element = new Element("blog""http://sjsky.javaeye.com");   
  15.          myCache.put(element);   
  16.          System.out.println("cache put Element");   
  17.          System.out.println("get Element value:= "  
  18.                  + myCache.get("blog").getValue());   
  19.          System.out.println("get Element objectvalue:= "  
  20.                  + myCache.get("blog").getObjectValue());   
  21.   
  22.          System.out.println("update the Element");   
  23.          myCache.put(new Element("blog""http://sjsky.iteye.com"));   
  24.          System.out.println("get Element value:= "  
  25.                  + myCache.get("blog").getValue());   
  26.          System.out.println("get Element objectvalue:= "  
  27.                  + myCache.get("blog").getObjectValue());   
  28.   
  29.          myCache.put(new Element("array"new String[] { "test""array" }));   
  30.          System.out.println("array value:= "  
  31.                  + myCache.get("array").getValue());   
  32.          myCache.remove("array");   
  33.          if (null == myCache.get("array")) {   
  34.              System.out.println("remove Element 'array' successful.");   
  35.          }   
  36.      } catch (Exception e) {   
  37.          e.printStackTrace(System.out);   
  38.      } finally {   
  39.          if (null != manager) {   
  40.              manager.shutdown();   
  41.          }   
  42.      }   
  43.  }  
 

      2.运行结果:

 

manager.getCache :[ name = MichaelInfo status = STATUS_ALIVE eternal = false overflowToDisk = true maxElementsInMemory = 100 maxElementsOnDisk = 100 memoryStoreEvictionPolicy = LRU timeToLiveSeconds = 120 timeToIdleSeconds = 120 diskPersistent = false diskExpiryThreadIntervalSeconds = 120 cacheEventListeners: net.sf.ehcache.statistics.LiveCacheStatisticsWrapper hitCount = 0 memoryStoreHitCount = 0 diskStoreHitCount = 0 missCountNotFound = 0 missCountExpired = 0 overflowToOffHeap = false maxMemoryOffHeap = null ]
cache put Element
get Element value:= http://sjsky.javaeye.com
get Element objectvalue:= http://sjsky.javaeye.com
update the Element
get Element value:= http://sjsky.iteye.com
get Element objectvalue:= http://sjsky.iteye.com
array value:= [Ljava.lang.String;@ec4a87
remove Element 'array' successful.
 

 

[五]、Cache的统计信息

      1.代码示例:

Java代码 复制代码
  1. /**  
  2.  * @blog http://sjsky.iteye.com <br>  
  3.  *       cache 信息统计  
  4.  */  
  5. public static void testCacheStatistics() {   
  6.     CacheManager manager = null;   
  7.     try {   
  8.         manager = new CacheManager();   
  9.         manager.addCache("MichaelInfo");   
  10.   
  11.         Cache myCache = manager.getCache("MichaelInfo");   
  12.   
  13.         myCache.put(new Element("username""Michael"));   
  14.         myCache.put(new Element("sex""男"));   
  15.         myCache.put(new Element("date"new Date()));   
  16.         myCache.put(new Element("height"172));   
  17.         myCache.put(new Element("position""cto"));   
  18.         myCache.put(new Element("blog""http://sjsky.iteye.com"));   
  19.   
  20.         System.out.println("cache size := " + myCache.getSize());   
  21.         System.out.println("MemoryStoreSize := "  
  22.                 + myCache.getMemoryStoreSize());   
  23.         System.out   
  24.                 .println("DiskStoreSize := " + myCache.getDiskStoreSize());   
  25.   
  26.         myCache.getStatistics().getDiskStoreObjectCount();   
  27.         System.out.println("Caceh getStatistics:");   
  28.         Statistics statistics = myCache.getStatistics();   
  29.         System.out.println("CacheHits := " + statistics.getCacheHits());   
  30.         System.out.println("CacheMisses := " + statistics.getCacheMisses());   
  31.         System.out.println("InMemoryHits := "  
  32.                 + statistics.getInMemoryHits());   
  33.         System.out.println("InMemoryMisses := "  
  34.                 + statistics.getInMemoryMisses());   
  35.         System.out.println("OnDiskHits := " + statistics.getOnDiskHits());   
  36.         System.out.println("OnDiskMisses := "  
  37.                 + statistics.getOnDiskMisses());   
  38.         System.out.println("MemoryStoreObjectCount := "  
  39.                 + statistics.getMemoryStoreObjectCount());   
  40.         System.out.println("DiskStoreObjectCount := "  
  41.                 + statistics.getDiskStoreObjectCount());   
  42.   
  43.         Element element = myCache.get("username");   
  44.         System.out.println("Element HitCount := " + element.getHitCount());   
  45.   
  46.     } catch (Exception e) {   
  47.         e.printStackTrace(System.out);   
  48.     } finally {   
  49.         if (null != manager) {   
  50.             manager.shutdown();   
  51.         }   
  52.     }   
  53. }  
 

      2.运行结果:

cache size := 6
MemoryStoreSize := 6
DiskStoreSize := 0
Caceh getStatistics:
CacheHits := 0
CacheMisses := 0
InMemoryHits := 0
InMemoryMisses := 0
OnDiskHits := 0
OnDiskMisses := 0
MemoryStoreObjectCount := 6
DiskStoreObjectCount := 0
Element HitCount := 1

 

[六]、测试所用两个的ehcache.xml文件

 

      1.classpath 下的: ehcache.xml (默认加载的配置文件)

Xml代码 复制代码
  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.   
  7.     <diskStore path="java.io.tmpdir"/>  
  8.   
  9.     <transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"  
  10.                               properties="jndiName=java:/TransactionManager" propertySeparator=";"/>  
  11.   
  12.     <cacheManagerEventListenerFactory class="" properties=""/>  
  13.   
  14.     <defaultCache  
  15.             maxElementsInMemory="100"  
  16.             eternal="false"  
  17.             timeToIdleSeconds="120"  
  18.             timeToLiveSeconds="120"  
  19.             overflowToDisk="true"  
  20.             diskSpoolBufferSizeMB="30"  
  21.             maxElementsOnDisk="100"  
  22.             diskPersistent="false"  
  23.             diskExpiryThreadIntervalSeconds="120"  
  24.             memoryStoreEvictionPolicy="LRU"  
  25.             statistics="false"  
  26.             />  
  27.   
  28.     <cache name="org.hibernate.cache.StandardQueryCache"  
  29.         maxElementsInMemory="5"    
  30.         eternal="false"    
  31.         timeToLiveSeconds="120"  
  32.         overflowToDisk="true" />  
  33.   
  34.     <cache name="org.hibernate.cache.UpdateTimestampsCache"  
  35.         maxElementsInMemory="5000"    
  36.         eternal="true"    
  37.         overflowToDisk="true" />  
  38.   
  39.     <cache name="sampleCache1"  
  40.            maxElementsInMemory="10000"  
  41.            maxElementsOnDisk="1000"  
  42.            eternal="false"  
  43.            overflowToDisk="true"  
  44.            diskSpoolBufferSizeMB="20"  
  45.            timeToIdleSeconds="300"  
  46.            timeToLiveSeconds="600"  
  47.            memoryStoreEvictionPolicy="LFU"  
  48.            transactionalMode="off"  
  49.             />  
  50.   
  51.     <cache name="sampleCache2"  
  52.            maxElementsInMemory="1000"  
  53.            eternal="true"  
  54.            overflowToDisk="false"  
  55.            memoryStoreEvictionPolicy="FIFO"  
  56.             />  
  57. </ehcache>  
 

 

      2.michael/hibernate/cache/ehcache/ehcache.xml(指定的配置文件)

Xml代码 复制代码
  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.   
  7.     <diskStore path="java.io.tmpdir"/>  
  8.   
  9.     <transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"  
  10.                               properties="jndiName=java:/TransactionManager" propertySeparator=";"/>  
  11.   
  12.   
  13.     <cacheManagerEventListenerFactory class="" properties=""/>  
  14.   
  15.     <cacheManagerPeerProviderFactory  
  16.             class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"  
  17.             properties="peerDiscovery=automatic,   
  18.                         multicastGroupAddress=230.0.0.1,   
  19.                         multicastGroupPort=4446timeToLive=1"   
  20.             propertySeparator=","  
  21.             />  
  22.     <cacheManagerPeerListenerFactory  
  23.             class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/>  
  24.   
  25.       
  26.     <defaultCache  
  27.             maxElementsInMemory="10000"  
  28.             eternal="false"  
  29.             timeToIdleSeconds="120"  
  30.             timeToLiveSeconds="120"  
  31.             overflowToDisk="true"  
  32.             diskSpoolBufferSizeMB="30"  
  33.             maxElementsOnDisk="10000000"  
  34.             diskPersistent="false"  
  35.             diskExpiryThreadIntervalSeconds="120"  
  36.             memoryStoreEvictionPolicy="LRU"  
  37.             statistics="false"  
  38.             />  
  39.     <cache name="sampleCache1"  
  40.            maxElementsInMemory="10000"  
  41.            maxElementsOnDisk="1000"  
  42.            eternal="false"  
  43.            overflowToDisk="true"  
  44.            diskSpoolBufferSizeMB="20"  
  45.            timeToIdleSeconds="300"  
  46.            timeToLiveSeconds="600"  
  47.            memoryStoreEvictionPolicy="LFU"  
  48.            transactionalMode="off"  
  49.             />  
  50.   
  51.     <cache name="sampleCache2"  
  52.            maxElementsInMemory="1000"  
  53.            eternal="true"  
  54.            overflowToDisk="false"  
  55.            memoryStoreEvictionPolicy="FIFO"  
  56.             />  
  57.   
  58.     <cache name="sampleCache3"  
  59.            maxElementsInMemory="500"  
  60.            eternal="false"  
  61.            overflowToDisk="true"  
  62.            timeToIdleSeconds="300"  
  63.            timeToLiveSeconds="600"  
  64.            diskPersistent="true"  
  65.            diskExpiryThreadIntervalSeconds="1"  
  66.            memoryStoreEvictionPolicy="LFU"  
  67.             />  
  68.   
  69.     <cache name="sampleReplicatedCache1"  
  70.            maxElementsInMemory="10"  
  71.            eternal="false"  
  72.            timeToIdleSeconds="100"  
  73.            timeToLiveSeconds="100"  
  74.            overflowToDisk="false">  
  75.   
  76.         <cacheEventListenerFactory  
  77.                 class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/>  
  78.         <bootstrapCacheLoaderFactory  
  79.                 class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/>  
  80.     </cache>  
  81.   
  82.     <cache name="sampleRepicatedCache2"  
  83.            maxElementsInMemory="10"  
  84.            eternal="false"  
  85.            timeToIdleSeconds="100"  
  86.            timeToLiveSeconds="100"  
  87.            overflowToDisk="false">  
  88.         <cacheEventListenerFactory  
  89.                 class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"  
  90.                 properties="replicateAsynchronously=falsereplicatePuts=false,   
  91.                             replicatePutsViaCopy=falsereplicateUpdates=true,   
  92.                             replicateUpdatesViaCopy=truereplicateRemovals=false"/>  
  93.     </cache>  
  94.   
  95.     <cache name="sampleReplicatedCache3"  
  96.            maxElementsInMemory="10"  
  97.            eternal="false"  
  98.            timeToIdleSeconds="100"  
  99.            timeToLiveSeconds="100"  
  100.            overflowToDisk="true">  
  101.         <cacheEventListenerFactory  
  102.                 class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"  
  103.                 properties="asynchronousReplicationIntervalMillis=200"/>  
  104.     </cache>  
  105. </ehcache>  
 

 

本文对EhCache的初步使用示例就讲到这,下面一节将讲一讲EhCache和Hibernate的集成应用示例:Hibernate+EhCache配置二级缓存的 (http://sjsky.iteye.com/blog/1312132)。

 

 

 

本文连接:http://sjsky.iteye.com/blog/1288257

 

 

 

转载请注明来自:Michael's blog @ http://sjsky.iteye.com


原创粉丝点击