OSCache-JSP頁面緩存(2)

若是在jsp中使用以下標籤css

<cache:cache key="foobar" scope="session"> 
      some jsp content 
</cache:cache>

那麼這中間的一段jsp代碼將會以key="foobar"緩存在session中,任何其餘頁面中使用這個key的cache標籤都能共享這段存在緩存中的執行結果。html

考慮一個需求,一個頁面是有許多個不一樣的jsp文件拼出來的,可能在頁首有隨機的廣告,登陸用戶的信息,系統的即時信息,固定的目錄信息等等;這其中能夠考慮將固定的目錄信息放入緩存中,而其餘動態信息則即時刷新;再進一步考慮有時候頁面之間的信息是關聯的,只有當其中一條信息的內容變化了才須要去刷新。java

對於這種需求就能夠考慮在<cache:cache/>標籤中配置group屬性,將不一樣的具備關聯關係的cache內容分組,這樣oscache會自動的幫你檢查該組緩存內容的變化狀況,若是有任何一子成員組的內容變化了則會執行刷新,這樣就能夠在頁面實現數據的動態同步。緩存

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@ taglib uri="http://www.opensymphony.com/oscache" prefix="cache"%>

<head>
    <title>Test Page</title>
    <style type="text/css">
body {
    font-family: Arial, Verdana, Geneva, Helvetica, sans-serif
}
</style>
</head>
<body>

    <a href="<%=request.getContextPath()%>/">Back to index</a>
    <p>
    <hr>
    Flushing 'group2'
    <hr>
    <cache:flush group='group2' scope='application' />
    <hr>
    <!-- 這裏有兩個cache分組group1和group2,將group2設置爲每次都執行刷新,因此test1爲key的cache每次刷新頁面內容都是從新執行過的 -->
    <cache:cache key='test1' groups='group1,group2' duration='5s'>
        <b>Cache Time1</b>: <%=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())%><br>  
         This is some cache content test1 that is in 'group1' and 'group2'. Normally it would refresh if it  
         was more than 5 seconds old, however the 
         <cache:flush group='group2' scope='application' />  
         tag causes this entry to be flushed on every page refresh.<br>
    </cache:cache>
    <hr>
    
    <!-- test2只有當間隔時間超過5秒纔會更新內容 -->
    <cache:cache key='test2' groups='group1' duration='5s'>
         <b>Cache Time2</b>: <%=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())%><br>  
         This is some cache content test2 that is in 'group1' (refreshes if more than 5 seconds old)<br>
    </cache:cache>
    <hr>

<!--每隔20秒刷新一次-> <cache:cache key='test3' duration='20s'> <b>Cache Time3</b>: <%=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())%><br> This is some cache content test3 that is in 'group1' and 'group2'. The groups are added using the tag.<br> </cache:cache> <hr>

<!--實時刷新--> <cache:cache key='test4' duration='20s'> <b>Cache Time4</b>: <%=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())%><br> This is some cache content test4 that is in 'group1' and 'group2'. The groups are added using the tag.<br> <cache:addgroups groups='group1,group2' /> </cache:cache> <hr> </body> </html>

<cache:addgroup group='{you_group}'/>能夠將所在的you_group加入當前所在位置的group中session

相關文章
相關標籤/搜索