天天看點

EhCache之初試

   blog遷移至 :http://www.micmiu.com

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.代碼示例:

/**
     * @blog http://sjsky.iteye.com <br>
     *       單例CacheManager 建立
     */
    public static void testCreateSingleton() {
        // Create a singleton CacheManager using defaults
        System.out.println("Create a singleton CacheManager using defaults");
        // CacheManager.create();
        System.out.println("CacheManager.create()     :="
                + CacheManager.getInstance());
        System.out.println("cacheNames length := "
                + CacheManager.getInstance().getCacheNames().length);
        CacheManager.getInstance().shutdown();

        System.out.println("=======================================");

        // Create a singleton CacheManager using a configuration file
        System.out
                .println("Create a singleton CacheManager using a configuration file");
        CacheManager singletonManager2 = CacheManager
                .create("src/main/java/michael/hibernate/cache/ehcache/ehcache.xml");
        System.out.println("CacheManager.create(file) :=" + singletonManager2);
        System.out.println("cacheNames length := "
                + singletonManager2.getCacheNames().length);
        System.out
                .println("CacheManager.getInstance() == singletonManager2 :: "
                        + (CacheManager.getInstance() == singletonManager2));
        singletonManager2.shutdown();
        // CacheManager.getInstance().shutdown();

        System.out.println("=======================================");

        // Create a singleton CacheManager from a configuration resource in the
        // classpath.
        URL configurl = Thread.currentThread().getContextClassLoader()
                .getResource("michael/hibernate/cache/ehcache/ehcache.xml");
        CacheManager singletonManager3 = CacheManager.create(configurl);
        System.out.println("CacheManager.create(url)  :=" + singletonManager3);

        String[] cacheNames = singletonManager3.getCacheNames();
        System.out.println("cacheNames length := " + cacheNames.length);
        for (String name : cacheNames) {
            System.out.println("name := " + name);
        }
        singletonManager3.shutdown();
        // CacheManager.getInstance().shutdown();
    }
           

      2.運作結果:

Create a singleton CacheManager using defaults

CacheManager.create() :[email protected]

cacheNames length := 4

=======================================

Create a singleton CacheManager using a configuration file

CacheManager.create(file) :[email protected]

cacheNames length := 6

CacheManager.getInstance() == singletonManager2 :: true

=======================================

CacheManager.create(url) :[email protected]

cacheNames length := 6

name := sampleRepicatedCache2

name := sampleReplicatedCache1

name := sampleCache2

name := sampleCache1

name := sampleReplicatedCache3

name := sampleCache3

[二]、多個CacheManager 建立

      1.代碼示例:

/**
     * @blog http://sjsky.iteye.com <br>
     *       CacheManager 建立
     */
    public static void testCreateManager() {

        // Create a CacheManager instance using defaults
        CacheManager manager1 = new CacheManager();
        System.out.println("new CacheManager()     := " + manager1);
        String[] cacheNames = manager1.getCacheNames();
        System.out.println("cacheNames length := " + cacheNames.length);
        for (String name : cacheNames) {
            System.out.println("name := " + name);
        }
        manager1.shutdown();

        System.out.println("=======================================");

        // Create a CacheManager instance using a configuration file
        CacheManager manager2 = new CacheManager(
                "src/main/java/michael/hibernate/cache/ehcache/ehcache.xml");
        System.out.println("new CacheManager(file) := " + manager2);
        System.out.println("cacheNames length := "
                + manager2.getCacheNames().length);
        manager2.shutdown();

        System.out.println("=======================================");
        // Create a singleton CacheManager from a configuration resource in the
        // classpath.
        URL configurl = Thread.currentThread().getContextClassLoader()
                .getResource("michael/hibernate/cache/ehcache/ehcache.xml");
        CacheManager manager3 = new CacheManager(configurl);
        System.out.println("new CacheManager(url)  := " + manager3);
        System.out.println("cacheNames length := "
                + manager3.getCacheNames().length);
        for (String name : manager3.getCacheNames()) {
            System.out.println("name := " + name);
        }
        manager3.shutdown();

    }
           

      2.運作結果:

new CacheManager() := [email protected]

cacheNames length := 4

name := sampleCache2

name := org.hibernate.cache.UpdateTimestampsCache

name := sampleCache1

name := org.hibernate.cache.StandardQueryCache

=======================================

new CacheManager(file) := [email protected]

cacheNames length := 6

=======================================

new CacheManager(url) := [email protected]

cacheNames length := 6

name := sampleRepicatedCache2

name := sampleReplicatedCache1

name := sampleCache2

name := sampleCache1

name := sampleReplicatedCache3

name := sampleCache3  

[三]、Cache的多種建立方式

      1.代碼示例: 

/**
     * @blog http://sjsky.iteye.com <br>
     *       Create Cache
     */
    public static void testCreateCache() {

        System.out.println("add cache with defaults:");
        CacheManager singletonManager = CacheManager.create();
        singletonManager.addCache("myCache1");
        Cache myCache1 = singletonManager.getCache("myCache1");
        System.out.println(myCache1);

        System.out.println("add cache with new Cache(arg1,arg2...):");
        Cache myMemoryCache = new Cache("myMemoryCache", 5000, false, false, 5,
                2);
        singletonManager.addCache(myMemoryCache);
        System.out.println(singletonManager.getCache("myMemoryCache"));

        System.out.println("Create a Cache specifying its configuration:");
        // Create a Cache specifying its configuration.
        int maxElements = 100;
        Cache myConfigCahce = new Cache(new CacheConfiguration("myConifgCahce",
                maxElements).memoryStoreEvictionPolicy(
                MemoryStoreEvictionPolicy.LFU).overflowToDisk(true).eternal(
                false).timeToLiveSeconds(60).timeToIdleSeconds(30)
                .diskPersistent(false).diskExpiryThreadIntervalSeconds(0));
        singletonManager.addCache(myConfigCahce);
        System.out.println(singletonManager.getCache("myConifgCahce"));

        singletonManager.shutdown();

    }
           

      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.代碼示例:

/**
     * @blog http://sjsky.iteye.com <br>
     *       CRUD operations
     */
    public static void testCacheElementCRUD() {
        CacheManager manager = null;
        try {
            manager = new CacheManager();
            manager.addCache("MichaelInfo");

            Cache myCache = manager.getCache("MichaelInfo");
            System.out.println("manager.getCache :" + myCache);

            Element element = new Element("blog", "http://sjsky.javaeye.com");
            myCache.put(element);
            System.out.println("cache put Element");
            System.out.println("get Element value:= "
                    + myCache.get("blog").getValue());
            System.out.println("get Element objectvalue:= "
                    + myCache.get("blog").getObjectValue());

            System.out.println("update the Element");
            myCache.put(new Element("blog", "http://sjsky.iteye.com"));
            System.out.println("get Element value:= "
                    + myCache.get("blog").getValue());
            System.out.println("get Element objectvalue:= "
                    + myCache.get("blog").getObjectValue());

            myCache.put(new Element("array", new String[] { "test", "array" }));
            System.out.println("array value:= "
                    + myCache.get("array").getValue());
            myCache.remove("array");
            if (null == myCache.get("array")) {
                System.out.println("remove Element 'array' successful.");
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        } finally {
            if (null != manager) {
                manager.shutdown();
            }
        }
    }
           

      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.代碼示例:

/**
     * @blog http://sjsky.iteye.com <br>
     *       cache 資訊統計
     */
    public static void testCacheStatistics() {
        CacheManager manager = null;
        try {
            manager = new CacheManager();
            manager.addCache("MichaelInfo");

            Cache myCache = manager.getCache("MichaelInfo");

            myCache.put(new Element("username", "Michael"));
            myCache.put(new Element("sex", "男"));
            myCache.put(new Element("date", new Date()));
            myCache.put(new Element("height", 172));
            myCache.put(new Element("position", "cto"));
            myCache.put(new Element("blog", "http://sjsky.iteye.com"));

            System.out.println("cache size := " + myCache.getSize());
            System.out.println("MemoryStoreSize := "
                    + myCache.getMemoryStoreSize());
            System.out
                    .println("DiskStoreSize := " + myCache.getDiskStoreSize());

            myCache.getStatistics().getDiskStoreObjectCount();
            System.out.println("Caceh getStatistics:");
            Statistics statistics = myCache.getStatistics();
            System.out.println("CacheHits := " + statistics.getCacheHits());
            System.out.println("CacheMisses := " + statistics.getCacheMisses());
            System.out.println("InMemoryHits := "
                    + statistics.getInMemoryHits());
            System.out.println("InMemoryMisses := "
                    + statistics.getInMemoryMisses());
            System.out.println("OnDiskHits := " + statistics.getOnDiskHits());
            System.out.println("OnDiskMisses := "
                    + statistics.getOnDiskMisses());
            System.out.println("MemoryStoreObjectCount := "
                    + statistics.getMemoryStoreObjectCount());
            System.out.println("DiskStoreObjectCount := "
                    + statistics.getDiskStoreObjectCount());

            Element element = myCache.get("username");
            System.out.println("Element HitCount := " + element.getHitCount());

        } catch (Exception e) {
            e.printStackTrace(System.out);
        } finally {
            if (null != manager) {
                manager.shutdown();
            }
        }
    }
           

      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 version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">

    <diskStore path="java.io.tmpdir"/>

    <transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"
                              properties="jndiName=java:/TransactionManager" propertySeparator=";"/>

    <cacheManagerEventListenerFactory class="" properties=""/>

    <defaultCache
            maxElementsInMemory="100"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            diskSpoolBufferSizeMB="30"
            maxElementsOnDisk="100"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
            statistics="false"
            />

    <cache name="org.hibernate.cache.StandardQueryCache"
    	maxElementsInMemory="5" 
    	eternal="false" 
    	timeToLiveSeconds="120"
    	overflowToDisk="true" />

    <cache name="org.hibernate.cache.UpdateTimestampsCache"
    	maxElementsInMemory="5000" 
    	eternal="true" 
    	overflowToDisk="true" />

    <cache name="sampleCache1"
           maxElementsInMemory="10000"
           maxElementsOnDisk="1000"
           eternal="false"
           overflowToDisk="true"
           diskSpoolBufferSizeMB="20"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off"
            />

    <cache name="sampleCache2"
           maxElementsInMemory="1000"
           eternal="true"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="FIFO"
            />
</ehcache>      

      2.michael/hibernate/cache/ehcache/ehcache.xml(指定的配置檔案)

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">

    <diskStore path="java.io.tmpdir"/>

    <transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"
                              properties="jndiName=java:/TransactionManager" propertySeparator=";"/>


    <cacheManagerEventListenerFactory class="" properties=""/>

    <cacheManagerPeerProviderFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
            properties="peerDiscovery=automatic,
                        multicastGroupAddress=230.0.0.1,
                        multicastGroupPort=4446, timeToLive=1"
            propertySeparator=","
            />
    <cacheManagerPeerListenerFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/>

   
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            diskSpoolBufferSizeMB="30"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
            statistics="false"
            />
    <cache name="sampleCache1"
           maxElementsInMemory="10000"
           maxElementsOnDisk="1000"
           eternal="false"
           overflowToDisk="true"
           diskSpoolBufferSizeMB="20"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off"
            />

    <cache name="sampleCache2"
           maxElementsInMemory="1000"
           eternal="true"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="FIFO"
            />

    <cache name="sampleCache3"
           maxElementsInMemory="500"
           eternal="false"
           overflowToDisk="true"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           diskPersistent="true"
           diskExpiryThreadIntervalSeconds="1"
           memoryStoreEvictionPolicy="LFU"
            />

    <cache name="sampleReplicatedCache1"
           maxElementsInMemory="10"
           eternal="false"
           timeToIdleSeconds="100"
           timeToLiveSeconds="100"
           overflowToDisk="false">

        <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/>
        <bootstrapCacheLoaderFactory
                class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/>
    </cache>

    <cache name="sampleRepicatedCache2"
           maxElementsInMemory="10"
           eternal="false"
           timeToIdleSeconds="100"
           timeToLiveSeconds="100"
           overflowToDisk="false">
        <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
                properties="replicateAsynchronously=false, replicatePuts=false,
                            replicatePutsViaCopy=false, replicateUpdates=true,
                            replicateUpdatesViaCopy=true, replicateRemovals=false"/>
    </cache>

    <cache name="sampleReplicatedCache3"
           maxElementsInMemory="10"
           eternal="false"
           timeToIdleSeconds="100"
           timeToLiveSeconds="100"
           overflowToDisk="true">
        <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
                properties="asynchronousReplicationIntervalMillis=200"/>
    </cache>
</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

----------------------------- 分 ------------------------------ 隔 ------------------------------ 線 ------------------------------