OsCache在Struts中的应用
? OsCache提供了一个管理类com.opensymphony.oscache.Web.ServletCacheAdministrator,通过 这个类,我们可以管理jsp页面定义的标签,下面看看在Struts的Action中,如何管理页面中的Cache标签的内容。业务逻辑如下:首先,用户 请求到Action中,该Action通过ServletCacheAdministrator实例来判断jsp页面是否已经失效(比如该Cache有效 期是10分钟),如果Cache标签失效了,那么重新取数据,否则直接forward到jsp页面,这样用户看到的就是经过缓存的jsp页面。以下是 Action 中的代码片:
??????? String normalImageOsGroup=null;//定义缓存的组
??????? try{
?????????? ServletCacheAdministrator admin=null;
?????????????? Cache oscache=null;
?????????????????? if(admin==null)
????????????????????? {
??????????????????????? admin=ServletCacheAdministrator.getInstance(this.getServlet().getServletContext());
???????????????????? }//if
???????????????????? if(oscache==null)
??????????????????? {
????????????????????? oscache=admin.getCache(req,PageContext.APPLICATION_SCOPE);
???????????????????? }//if
?????????????????? //取得group为mygroup ,key为persion_msg的缓存
???????????????? normalImageOsGroup="mygroup";
???????????????? String OsEntryKey=admin.generateEntryKey("persion_msg",request,PageContext.APPLICATION_SCOPE);
????????????????? Object osobj=oscache.getFromCache(OsEntryKey,600);//判断缓存10分钟的期限是否已经到了
?????????????????? /*
??????????????????? 如果已超出指定的Cache有效期600秒,将报NeedsRefreshException异常,
???????????????????? 这样我们就通过异常处理部分来重新取得数据,然后传递给页面使用。
???????????????????? */
?
?????? }catch(NeedsRefreshException? nrfe){
?????????? log.warn("OsCache已经过期,需要重新添加数据");
????????? String oldCache=(String)nrfe.getCacheContent();//取得数据
???????????//为了避免死锁因为NeedsRefreshException产生时,如果不调用update或者put得相关操作,osCache将锁该cache
????????? oscache.putInCache(OsEntryKey,oldCache,new String[]{normalImageOsGroup});
????????? //刷新该key,使页面的oscache失效
????????? oscache.flushEntry(OsEntryKey);
??????? }
????? 以下是jsp页面代码:
????? < %@page contentType="text/html;charset=GBK"% >
???? <?% @taglib uri="oscache" prefix="cache" % >
???? <?%
????????? Person ps=(Person)request.getAttribute("PersonObject");
?? % >
??? <html>
???? <head>
??? <body>
?? <cache:cache key="persion_msg" time="-1" groups="mygroup">
?????????<%?
?????????? if(ps!=null){
???????????? out.println("Person Name:"+ps.getName());
????????? }//if
??????? %>
?
<cache:cache>
</body>
</html>