<!--[if !supportLists]-->1.      <!--[endif]-->類圖

CacheManager

Cache

Element

Cache

Cache

Element

<!--[if !vml]--><!--[endif]-->

<!--[if !supportLists]-->2.      <!--[endif]-->概述

Ehcache的類層次模型主要為三層,最上層的是CacheManager,他是操作Ehcache的入口。我們可以通過CacheManager.getInstance()獲得一個(gè)單子的CacheManger,或者通過CacheManger的構(gòu)造函數(shù)創(chuàng)建一個(gè)新的CacheManger。每個(gè)CacheManager都管理著多個(gè)Cache。而每個(gè)Cache都以一種類Hash的方式,關(guān)聯(lián)著多個(gè)Element。而Element則是我們用于存放要緩存內(nèi)容的地方。

<!--[if !supportLists]-->3.      <!--[endif]-->配置文件

<!--[if !supportLists]-->a)        <!--[endif]-->參考:http://ehcache.sourceforge.net/documentation/configuration.html

<!--[if !supportLists]-->b)        <!--[endif]-->例子:

<ehcache xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance

 xsi:noNamespaceSchemaLocation="ehcache.xsd">

              <defaultCache maxElementsInMemory="2" eternal="false" timeToIdleSeconds="1"

                timeToLiveSeconds="1" overflowToDisk="false" memoryStoreEvictionPolicy="LRU"/>

    <cache name="sampleCache1" maxElementsInMemory="2" eternal="false"

overflowToDisk="false" timeToIdleSeconds="1" timeToLiveSeconds="1"

           memoryStoreEvictionPolicy="LRU"/>

</ehcache>

注:在ehcache的配置文件里面必須配置defaultCache。每個(gè)<cache>標(biāo)簽定義一個(gè)新的cache,屬性的含義基本上可以從名字上得到,詳細(xì)的說明可以參考上面的鏈接。

<!--[if !supportLists]-->4.      <!--[endif]-->事例程序:

<!--[if !supportLists]-->a)        <!--[endif]-->例子:

publicclass Test {

     publicstaticvoid main(String[] args) throws Exception {

         CacheManager manager = new CacheManager("ehcache.xml");

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

        

         for (int i = 0; i < 5; i++) {

              Element e = new Element("key" + i, "value" + i);

              cache.put(e);

         }

         List<String> keys = cache.getKeys();

         for (String key : keys) {

              System.out.println(key + "," + cache.get(key));

         }

     }

}

注:程序的流程也是比較明晰的,首先是獲取一個(gè)CacheManager,這是使用Ehcache的入口,然后通過名字獲取某個(gè)Cache,然后就可以對(duì)Cache存取Element。Cache使用類Hash的方式來管理Element。

<!--[if !supportLists]-->5.      <!--[endif]-->事件處理

<!--[if !supportLists]-->a)        <!--[endif]-->說明:可以為CacheManager添加事件監(jiān)聽,當(dāng)對(duì)CacheManager增刪Cache時(shí),事件處理器將會(huì)得到通知。要配置事件處理,需要通過ehcache的配置文件來完成。

<!--[if !supportLists]-->b)        <!--[endif]-->配置文件:

<ehcache>

<cacheManagerEventListenerFactory class="ehcache.CMELF"/>

</ehcache>

注:通過<cacheManagerEventListenerFactory>來注冊(cè)事件處理器的工廠類。

<!--[if !supportLists]-->c)        <!--[endif]-->代碼:

publicclass CMELF extends CacheManagerEventListenerFactory {

     @Override

     public CacheManagerEventListener createCacheManagerEventListener(

              Properties properties) {

         returnnew CMEL();

     }

}

class CMEL implements CacheManagerEventListener {

     publicvoid dispose() throws CacheException {}

     public Status getStatus() {returnnull;}

     publicvoid init() throws CacheException {}

     publicvoid notifyCacheAdded(String cacheName) {

         System.out.println("Cache [" + cacheName + "] Added");

     }

     publicvoid notifyCacheRemoved(String cacheName) {

         System.out.println("Cache [" + cacheName + "] Deleted");

     }

}

注:這個(gè)代碼分為兩部分,首先是一個(gè)工廠類,用于創(chuàng)建事件處理器事例,工廠類負(fù)責(zé)還需要管理并發(fā)之類的問題。

<!--[if !supportLists]-->6.      <!--[endif]-->事件處理

<!--[if !supportLists]-->a)        <!--[endif]-->說明:可以為Cache添加事件監(jiān)聽,當(dāng)對(duì)Cache增刪Element時(shí),事件處理器將會(huì)得到通知。要配置事件處理,需要通過ehcache的配置文件來完成。

<!--[if !supportLists]-->b)        <!--[endif]-->配置文件:

<ehcache>

<cache name="sampleCache1">

<cacheEventListenerFactory class="ehcache.CELF"/>

     </cache>

</ehcache>

<!--[if !supportLists]-->c)        <!--[endif]-->代碼:

publicclass CELF extends CacheEventListenerFactory {

     @Override

     public CacheEventListener createCacheEventListener(Properties properties) {

         returnnew CEL();

     }

}

class CEL implements CacheEventListener {

     publicvoid dispose() {}

     publicvoid notifyElementEvicted(Ehcache cache, Element element) {}

     publicvoid notifyElementExpired(Ehcache cache, Element element) {}

     publicvoid notifyElementPut(Ehcache cache, Element element)

              throws CacheException {

         System.out.println(element.getKey() + " was added.");

     }

     publicvoid notifyElementRemoved(Ehcache cache, Element element)

              throws CacheException {

         System.out.println(element.getKey() + " was removed.");

     }

     publicvoid notifyElementUpdated(Ehcache cache, Element element)

              throws CacheException {}

     publicvoid notifyRemoveAll(Ehcache cache) {}

     @Override

     public Object clone() throws CloneNotSupportedException {

         returnsuper.clone();

     }

}

注:這里的代碼與之前的類似,由此可見Ehcache的事件處理采用的是一種類plugin方式,也就是說,事件處理的添加是以不修改源代碼為前提的。

<!--[if !supportLists]-->7.      <!--[endif]-->Hibernate中使用Ehcache

<!--[if !supportLists]-->a)        <!--[endif]-->說明:要在hibernate中使用Ehcache,需要修改3個(gè)文件。

<!--[if !supportLists]-->b)        <!--[endif]-->ehcache.xml

<ehcache>

     <defaultCache/>  

     <cache name="objCache"/>

</ehcache>

注:這里我們創(chuàng)建了一個(gè)名為“objCache”的緩存。

<!--[if !supportLists]-->c)        <!--[endif]-->hibernate.cfg.xml

<hibernate-configuration>

     <session-factory>

         <property name="hibernate.cache.provider_class">

              org.hibernate.cache.EhCacheProvider

         </property>

         <property name="hibernate.cache.use_second_level_cache">true</property>

         <property name="hibernate.cache.provider_configuration_file_resource_path">

              ehcache.xml

         </property>

         <property name="hibernate.generate_statistics">true</property>

     </session-factory>

</hibernate-configuration>

注:這里我們聲明了要使用的緩存類型為Ehcache,并指定了配置文件的地址。

<!--[if !supportLists]-->d)        <!--[endif]-->mapping

<hibernate-mapping>

     <class>

         <cache usage="read-write" region="objCache"/>

         <id name="id" column="id" type="java.lang.Integer">

              <generator class="native"></generator>

         </id>

         <property name="name" type="string"></property>

         <property name="age" type="int"></property>

     </class>

</hibernate-mapping>

注:這里,我們usage指名了什么樣的操作需要使用cache,而region指明了在那個(gè)cache上進(jìn)行操作,如果不聲明region,則在defaultCache上操作。