Ehcache學習總結

     做的項目暫告一個段落,想優化一下性能的,到網上查了一下搜得寶物ehcache。最終發現ehcache並非是想象的那樣簡單,現記錄下過程,希望其他人少走彎路。

 

     先獲得的信息是spring如何配置ehcache,這是ehcache的第一種用法,利用spring的aop,定製兩個interceptor,一爲執行方法時,將查詢結果放入cache,如果在cache中已經存在,則直接從cache中取出。主要針對查詢動作(以class名+方法名+參數名作爲key);一爲方法執行後,在諸如update,delete,create的動作後刪除相關cache內的內容。通過spring的applicationContext配置後即可使用,網上有很多的例子,單獨架設起來並不困難,也可以順利跑通。但當我想整合到項目中時卻發現tomcat報錯,總是說sesstionFactory無法初始化,無法初始化的原因是com.mchange.v2.c3p0.ComboPooledDataSource 不能被cast成serializable類型,看了一下出錯的地方,是第一個interceptor方法裏面有一句element = new Element(cacheKey, (Serializable) result);。網上也沒有什麼解釋,看來是沒有什麼人這樣用。回頭想一下也確實是,在spring這一層加上cache能緩存什麼內容呢?至少目前的這個障礙還無法逾越,只好繼續去網上搜索。

 

     接下來看到的是hibernate如何配置ehcache,這個配置不是很複雜,主要是在聲明hibernate的地方,加上如下三句話,告訴spring,hibernate需要用ehcache作爲二級緩存:

                <prop key="hibernate.cache.use_second_level_cache">true</prop>               
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>               
                <prop key="hibernate.cache.use_query_cache">true</prop>

 

然後,在對應的xxx.hbm.xml裏,class之後,id之前註明cache讀寫的類型,

                <cache usage="nonstrict-read-write"></cache>

 

最後在對應的dao中設定getHibernateTemplate().setCacheQuery(true), 這樣就可以了。

 

     最後一種是在查詢過程中發現的副產品,對網頁的cache,這裏主要是在web.xml中進行配置,設定好filter和filtermapping,如下:

     <filter>
         <filter-name>indexCacheFilter</filter-name>
         <filter-class>
               net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter
          </filter-class>

          <init-param>
            <param-name>cacheName</param-name>
            <param-value>MyCache</param-value>
        </init-param>
    </filter>
 
    <filter-mapping>
        <filter-name>indexCacheFilter</filter-name>
        <url-pattern>*.jsp</url-pattern>
      </filter-mapping>

 

其中MyCache是ehcache.xml中cache的名稱,可以自己定製。另外還有Gzip的配置,對壓縮js,css比較適合。

     <filter>
        <filter-name>GzipFilter</filter-name>
        <filter-class>net.sf.ehcache.constructs.web.filter.GzipFilter</filter-class>
        <init-param>
            <param-name>exceptionsToLogDifferently</param-name>
            <param-value>net.sf.ehcache.CacheException, java.lang.NullPointerException
            </param-value>
        </init-param>
        <init-param>
            <param-name>exceptionsToLogDifferentlyLevel</param-name>
            <param-value>fatal</param-value>
        </init-param>
        <init-param>
            <param-name>suppressStackTraces</param-name>
            <param-value>false</param-value>
        </init-param>
    </filter>

 

     另外,在查詢過程中,還發現ehcache有不同種類的cache,class cache, query cache以及collection cache,另外對cache如何合理配置的問題需要再花時間研究。

 

     SSH的框架確實靈活,有時也會因爲選擇太多而困惑。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章