oscache的简单应用配置介绍

1. OSCache是什么    

OSCache标记库由OpenSymphony设计,它是一种开创性的JSP定制标记应用,提供了在现有JSP页面之内实现快速内存缓冲的功能。OSCache是个一个广泛采用的高性能的J2EE缓存框架,OSCache能用于任何Java应用程序的普通的缓存解决方案。OSCache有以下特点:缓存任何对象,你可以不受限制的缓存部分jsp页面或HTTP请求,任何java对象都可以缓存。拥有全面的API--OSCache API给你全面的程序来控制所有的OSCache特性。永久缓存--缓存能随意的写入硬盘,因此允许昂贵的创建(expensive-to-create)数据来保持缓存,甚至能让应用重启。支持集群--集群缓存数据能被单个的进行参数配置,不需要修改代码。缓存记录的过期--你可以有最大限度的控制缓存对象的过期,包括可插入式的刷新策略(如果默认性能不需要时)。

2. 官方下载地址:http://www.opensymphony.com/oscache/download.action

3. OSCache的安装配置

(1)从下载后解压缩目录中取得oscache.jar 文件放到 /WEB-INF/lib 或相应类库目录 目录中,jar文件名可能含有版本号和该版本的发布日期信息等,如oscache-2.0.2-22Jan04.jar。如果你的jdk版本为1.3.x,建议在lib中加入Apache Common Lib 的commons-collections.jar包。如jdk是1.4以上则不必。

从src或etc目录取得oscache.properties 文件,放入src根目录或发布环境的/WEB-INF/classes 目录。如你需要建立磁盘缓存,须修改oscache.properties 中的cache.path信息 (去掉前面的#注释)。
win类路径类似为c:\\app\\cache      unix类路径类似为/opt/myapp/cache

如果在页面上要用到OSCache,则需要拷贝OSCache标签库文件oscache.tld到/WEB-INF/classes目录(如果不需要页面缓存,则此文件可不添加),

并将下列代码加入web.xml文件中
<taglib>
<taglib-uri>oscache</taglib-uri>
<taglib-location>/WEB-INF/classes/oscache.tld</taglib-location>
</taglib>

为了便于调试日志输出,须加入commons-logging.jar和log4j-1.2.8.jar到当前类库路径中

在src目录加入下面两个日志输出配置文件:
log4j.properties 文件内容为:
log4j.rootLogger=DEBUG,stdout,file
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[start]%d{yyyy/MM/dd/ HH:mm:ss}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD] n%c[CATEGORY]%n%m[MESSAGE]%n%n

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=oscache.log
log4j.appender.file.MaxFileSize=100KB
log4j.appender.file.MaxBackupIndex=5
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[start]%d{yyyy/MM/dd/ HH:mm:ss}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD] n%c[CATEGORY]%n%m[MESSAGE]%n%n

log4j.logger.org.apache.commons=ERROR
log4j.logger.com.opensymphony.oscache.base=INFO

commons-logging.properties 文件内容为org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JCategoryLog

(2)oscache.properties 文件配置

cache.memory     值为true 或 false ,默认为在内存中作缓存,如设置为false,那cache只能缓存到数据库或硬盘中;

cache.capacity     缓存元素个数;

cache.persistence.class       持久化缓存类,如此类打开,则必须设置cache.path信息
cache.cluster       相关为集群设置信息。如cache.cluster.multicast.ip为广播IP地址;cache.cluster.properties为集群属性
4. OSCache具体应用

(1)页面应用

在web.xml进行一些简单的配置,把oscache.tld放到WEB-INF/classes下,并在web.xml中添加如下

<jsp-config>
  <taglib>
   <taglib-uri>oscache</taglib-uri>
   <taglib-location>
    /WEB-INF/classes/oscache.tld
   </taglib-location>
  </taglib>
 </jsp-config>

具体页面中需要简单的引用

<%@ page import="java.util.*" %>
<%@ taglib uri="oscache" prefix="cache" %>

<html>
<body>

没有缓存的日期: <%= new Date() %><p>
<!--自动刷新-->
<cache:cache time="30">
每30秒刷新缓存一次的日期: <%= new Date() %>
</cache:cache>
<!--手动刷新-->
<cache:cache key="testcache">
手动刷新缓存的日期: <%= new Date() %> <p>
</cache:cache>
<a href="cache2.jsp">手动刷新</a>

</body>
</html>

cache2.jsp 执行手动刷新页面如下
<%@ taglib uri="oscache" prefix="cache" %>

<html>
<body>

缓存已刷新...<p>

<cache:flush key="testcache" scope="application"/>

<a href="cache1.jsp">返回</a>

</body>
</html>
你也可以通过下面语句定义Cache的有效范围,如不定义scope,scope默认为Applcation
<cache:cache time="30" scope="session">
...
</cache:cache>

如果想针对某一页面类型进行缓存,则可以利用过滤器来配置,在web.xm中可添加代码

<!-- OScacheFilter  -->
 <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>3600</param-value>
  </init-param>
  <init-param>
   <param-name>scope</param-name>
   <param-value>application</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>CacheFilter</filter-name>
  <url-pattern>*.ftl</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>CacheFilter</filter-name>
  <url-pattern>*.jsp</url-pattern>
 </filter-mapping>
 <!-- OScacheFilter  -->

另外,如果想对某一访问的路径action进行缓存的话,我们可以这样做,在一个jsp文件中简单的加上:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ taglib uri="oscache" prefix="cache" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <title>My JSP 'index.jsp' starting page</title>
 </head>
 <body>
  <oscache:cache>
   <jsp:include page ="/view.do"/>
  </oscache:cache>
 </body>
</html>

其中注意,CacheFilter只捕获Http头为200的页面请求,即只对无错误请求作缓存,而不对其他请求(如500,404,400)作缓存处理(错误请求缓存有用吗?呵呵)

虽然它专门为jsp提供了强大的标签支持,并不意味着不能对ftl,php进行缓存的,我们可以用jsp中的标签来嵌套我们的返回不同的数据页面。比如上面的/view.do可以返回的是一个ftl页面,照样可以缓存。

 (2)对象缓存

基于GeneralCacheAdministrator类来写的BaseCache类

package com.klstudio.cache;

import java.util.Date;

import com.opensymphony.oscache.base.NeedsRefreshException;
import com.opensymphony.oscache.general.GeneralCacheAdministrator;

public class BaseCache extends GeneralCacheAdministrator {
 //过期时间(单位为秒);
 private int refreshPeriod;
 //关键字前缀字符;
 private String keyPrefix; 
 private static final long serialVersionUID = -4397192926052141162L; 
 public BaseCache(String keyPrefix,int refreshPeriod){
  super();
  this.keyPrefix = keyPrefix;
  this.refreshPeriod = refreshPeriod;
 }
 //添加被缓存的对象;
 public void put(String key,Object value){
  this.putInCache(this.keyPrefix+"_"+key,value);
 }
 //删除被缓存的对象;
 public void remove(String key){
  this.flushEntry(this.keyPrefix+"_"+key);
 }
 //删除所有被缓存的对象;
 public void removeAll(Date date){
  this.flushAll(date);
 } 
 public void removeAll(){
  this.flushAll();
 }
 //获取被缓存的对象;
 public Object get(String key) throws Exception{
  try{
   return this.getFromCache(this.keyPrefix+"_"+key,this.refreshPeriod);
  } catch (NeedsRefreshException e) {
   this.cancelUpdate(this.keyPrefix+"_"+key);
   throw e;
  }

 } 
}

Java代码

package com.klstudio.cache;

import java.util.Date;

import com.opensymphony.oscache.base.NeedsRefreshException;
import com.opensymphony.oscache.general.GeneralCacheAdministrator;

public class BaseCache extends GeneralCacheAdministrator {
 //过期时间(单位为秒);
 private int refreshPeriod;
 //关键字前缀字符;
 private String keyPrefix; 
 private static final long serialVersionUID = -4397192926052141162L; 
 public BaseCache(String keyPrefix,int refreshPeriod){
  super();
  this.keyPrefix = keyPrefix;
  this.refreshPeriod = refreshPeriod;
 }
 //添加被缓存的对象;
 public void put(String key,Object value){
  this.putInCache(this.keyPrefix+"_"+key,value);
 }
 //删除被缓存的对象;
 public void remove(String key){
  this.flushEntry(this.keyPrefix+"_"+key);
 }
 //删除所有被缓存的对象;
 public void removeAll(Date date){
  this.flushAll(date);
 } 
 public void removeAll(){
  this.flushAll();
 }
 //获取被缓存的对象;
 public Object get(String key) throws Exception{
  try{
   return this.getFromCache(this.keyPrefix+"_"+key,this.refreshPeriod);
  } catch (NeedsRefreshException e) {
   this.cancelUpdate(this.keyPrefix+"_"+key);
   throw e;
  }

 } 
}

 

package com.klstudio;

import com.klstudio.News;
import com.klstudio.cache.BaseCache;

public class CacheManager { 
 private BaseCache newsCache; 
 private static CacheManager instance;
 private static Object lock = new Object(); 
 public CacheManager() {
     //这个根据配置文件来,初始BaseCache而已;
  newsCache = new BaseCache("news",1800);  
 } 
 public static CacheManager getInstance(){
  if (instance == null){
   synchronized( lock ){
    if (instance == null){
     instance = new CacheManager();
    }
   }
  }
  return instance;
 }

 public void putNews(News news) {
  // TODO 自动生成方法存根
  newsCache.put(news.getID(),news);
 }

 public void removeNews(String newsID) {
  // TODO 自动生成方法存根
  newsCache.remove(newsID);
 }

 public News getNews(String newsID) {
  // TODO 自动生成方法存根
  try {
   return (News) newsCache.get(newsID);
  } catch (Exception e) {
   // TODO 自动生成 catch 块
   System.out.println("getNews>>newsID["+newsID+"]>>"+e.getMessage());
   News news = new News(newsID);
   this.putNews(news);
   return news;
  }
 }

 public void removeAllNews() {
  // TODO 自动生成方法存根
  newsCache.removeAll();
 }

}

 Java代码

package com.klstudio;

import com.klstudio.News;
import com.klstudio.cache.BaseCache;

public class CacheManager { 
 private BaseCache newsCache; 
 private static CacheManager instance;
 private static Object lock = new Object(); 
 public CacheManager() {
     //这个根据配置文件来,初始BaseCache而已;
  newsCache = new BaseCache("news",1800);  
 } 
 public static CacheManager getInstance(){
  if (instance == null){
   synchronized( lock ){
    if (instance == null){
     instance = new CacheManager();
    }
   }
  }
  return instance;
 }

 public void putNews(News news) {
  // TODO 自动生成方法存根
  newsCache.put(news.getID(),news);
 }

 public void removeNews(String newsID) {
  // TODO 自动生成方法存根
  newsCache.remove(newsID);
 }

 public News getNews(String newsID) {
  // TODO 自动生成方法存根
  try {
   return (News) newsCache.get(newsID);
  } catch (Exception e) {
   // TODO 自动生成 catch 块
   System.out.println("getNews>>newsID["+newsID+"]>>"+e.getMessage());
   News news = new News(newsID);
   this.putNews(news);
   return news;
  }
 }

 public void removeAllNews() {
  // TODO 自动生成方法存根
  newsCache.removeAll();
 }

}


相关链接:http://blog.csdn.net/ezerg/archive/2004/10/14/135769.aspx 
 http://blog.csdn.net/weijie_search/archive/2008/03/31/2232435.aspx

http://southking.javaeye.com/blog/252805

转载于:https://www.cnblogs.com/heyanzheng/articles/1664860.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值