先記一下,blogjava上不了。
ehcache做頁面部分緩存,配置有點麻煩,操作也有點複雜,不過感覺還是很好用。
首先看web.xml配置:
增加以下配置:
<!--ehcache web page cache -->
<filter>
<filter-name>fragmentcache</filter-name>
<filter-class>net.sf.ehcache.constructs.web.filter.simplepagefragmentcachingfilter
</filter-class>
<init-param>
<param-name>suppressstacktraces</param-name>
<param-value>false</param-value>
</init-param>
<param-name>cachename</param-name>
<param-value>fragmentcache</param-value>
</filter>
<!--
this is a filter chain. they are executed in the order below. do not
change the order.
-->
<filter-mapping>
<url-pattern>/web-inf/pages/tour/tourdetailbody.jsp</url-pattern>
<dispatcher>include</dispatcher>
</filter-mapping>
注意,那個<dispatcher>include</dispatcher>,不能少,少了緩存不能用。
配置中對應<jsp:include page="/web-inf/pages/tour/tourdetailbody.jsp"/>
2.4版本的servlet規範在部屬描述符中新增加了一個<dispatcher>元素,這個元素有四個可能的值:即request,forward,include和error,可以在一個<filter-mapping>元素中加入任意數目的<dispatcher>,使得filter将會作用于直接從用戶端過來的request,通過forward過來的request,通過include過來的request和通過<error-page>過來的request。如果沒有指定任何< dispatcher >元素,預設值是request。
<?xml version="1.0" encoding="utf-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:nonamespaceschemalocation="../../main/config/ehcache.xsd">
<diskstore path="java.io.tmpdir" />
<defaultcache
maxelementsinmemory="10"
eternal="false"
timetoidleseconds="5"
timetoliveseconds="10"
overflowtodisk="true" />
maxelementsinmemory="10"記憶體中的最大頁面對象
timetoidleseconds="120" timetoidleseconds ,多長時間不通路該緩存,那麼ehcache就會清除該緩存。
timetoliveseconds="240" timetoliveseconds,緩存的存活時間,從開始建立的時間算起。
overflowtodisk="true" 是否寫入硬碟
<!-- page and page fragment caches -->
<cache name="fragmentcache"
timetoidleseconds="10000"
timetoliveseconds="10000"
overflowtodisk="true">
</cache>
</ehcache>
資料的更新問題:
和頁面緩存一樣的,根據配置檔案中的cachename擷取ehcache,再根據擷取的key進行remove操作。
action中的問題:當頁面請求發生時,會調用action方法,這時我們因為先方法,應該先查詢cache中是否有緩存fragment存在,如果有,直接傳回成功頁面,如果沒有則執行剩下的代碼。