OSCache使用經驗總結
OSCache使用經驗總結
OSCache的使用主要有4種:
POJO 緩衝
HTTP Response 緩衝
JSP Tag Library 緩衝
O/R Data Access 緩衝
1、POJO 緩衝
這種方式的緩衝直接調用OSCache的API進行,主要用於處理頁面內容會根據參數動態改變,可以將參數設定為key值來儲存資料:
首先,聲明成員變數:
// OSCache Adminitrator instance
private static GeneralCacheAdministrator cacheAdmin = null;
其次,進行初始化:
public RingArtistAction() {
cacheAdmin = new GeneralCacheAdministrator();
}
將POJO進行緩衝:
// Cache data key and refresh period
String key = sex + ":" + place;
int refreshPeriod = Constants.getIntegerValue(Constants.OSCACHE_REFRESH_PERIOD).intValue();
try {
// Get from the cache
artists = (Map) cacheAdmin.getFromCache(key, refreshPeriod);
} catch (NeedsRefreshException nre) {
try {
// Get the value (probably from the database)
int count = getArtistCount(sex, place, errors);
artists = getArtistData(sex, place, count, errors);
// Store in the cache
cacheAdmin.putInCache(key, artists);
} catch (Exception ex) {
// We have the current content if we want fail-over.
artists = (Map) nre.getCacheContent();
// It is essential that cancelUpdate is called if the
// cached content is not rebuilt
cacheAdmin.cancelUpdate(key);
ex.printStackTrace();
}
}
2、HTTP Response 緩衝
這種方式的緩衝用來處理整個頁面的內容固定,不會根據參數動態改變:
首先在web.xml中配置CacheFilter:
<filter>
<filter-name>CacheFilter</filter-name>
<filter-class>com.opensymphony.oscache.web.filter.CacheFilter</filter-class>
<init-param>
<param-name>time</param-name>
<param-value>86400</param-value>
</init-param>
<init-param>
<param-name>scope</param-name>
<param-value>application</param-value>
</init-param>
</filter>
將所有需要緩衝的頁面加入filter-mapping:
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
注意,只有返回狀態為200(HttpServletResponse.SC_OK)的內容才會被緩衝
3、JSP Tag 緩衝
JSP Tag緩衝主要用於緩衝JSP頁面的局部內容:
<cache:cache key="especialcategory" cron="* 5 * * *">
<jsp:include page="/ringcategory.do" flush="true" >
<jsp:param name="ringType" value="1"/>
</jsp:include>
</cache:cache>
4、O/R Data Access 緩衝
請閱讀參考資料的內容擷取詳情。
zz:http://www.blogjava.net/jackstudio/archive/2006/09/08/68569.html