OSCache缓存

1OSCache是什么?

     OSCache标记库由OpenSymphony设计,它是一种开创性的缓存方案,它提供了在现有JSP页面之内实现内存缓存的功能。OSCache是个一个

被广泛采用的高性能的J2EE缓存框架,OSCache还能应用于任何Java应用程序的普通的缓存解决方案。

2OSCache的特点

    (1) 缓存任何对象:你可以不受限制的缓存部分jsp页面或HTTP请求,任何java对象都可以缓存。

    (2) 拥有全面的APIOSCache API允许你通过编程的方式来控制所有的OSCache特性。

    (3) 永久缓存:缓存能被配置写入硬盘,因此允许在应用服务器的多次生命周期间缓存创建开销昂贵的数据。

    (4) 支持集群:集群缓存数据能被单个的进行参数配置,不需要修改代码。

    (5) 缓存过期:你可以有最大限度的控制缓存对象的过期,包括可插入式的刷新策略(如果默认性能不能满足需要时)。

3OSCache的安装与配置

    OSCache是当前运用最广的缓存方案,JBoss,Hibernate,Spring等都对其有支持,

下面简单介绍一下OSCache的配置和使用过程。

 

1.安装过程

http://www.opensymphony.com/oscache/download.html下载合适的OSCache版本,

我下载的是oscache-2.0.2-full版本。

解压缩下载的文件到指定目录

 

从解压缩目录取得oscache.jar 文件放到 /WEB-INF/lib 或相应类库目录目录中,

jar文件名可能含有版本号和该版本的发布日期信息等,如oscache-2.0.2-22Jan04.jar

 

如果你的jdk版本为1.3.x,建议在lib中加入Apache Common Lib commons-collections.jar包。

jdk1.4以上则不必

 

srcetc目录取得oscache.properties文件,放入src根目录或发布环境的/WEB-INF/classes目录

如你需要建立磁盘缓存,须修改oscache.properties中的cache.path信息 (去掉前面的#注释)

win类路径类似为c://app//cache

unix类路径类似为/opt/myapp/cache

 

拷贝OSCache标签库文件oscache.tld/WEB-INF/classes目录。

 

现在你的应用目录类似如下:

$WEB_APPLICATION/WEB-INF/lib/oscache.jar

$WEB_APPLICATION/WEB-INF/classes/oscache.properties

$WEB_APPLICATION/WEB-INF/classes/oscache.tld

 

 

将下列代码加入web.xml文件中

<taglib>

<taglib-uri>oscache</taglib-uri>

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

</taglib>

 

为了便于调试日志输出,须加入commons-logging.jarlog4j-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还有什么意义:)

 

cache.capacity

缓存元素个数

 

cache.persistence.class

持久化缓存类,如此类打开,则必须设置cache.path信息

 

cache.cluster 相关

为集群设置信息。

cache.cluster.multicast.ip为广播IP地址

cache.cluster.properties为集群属性

 

 

3.OSCache的基本用法

 

cache1.jsp 内容如下

 

<%@ pageimport="java.util.*" %>

<%@ taglib uri="oscache"prefix="cache" %>

 

<html>

<body>

 

没有缓存的日期: <%= newDate() %><p>

<!--自动刷新-->

<cache:cache time="30">

30秒刷新缓存一次的日期: <%= new Date() %>

</cache:cache>

<!--手动刷新-->

<cache:cachekey="testcache">

手动刷新缓存的日期: <%= newDate() %> <p>

</cache:cache>

<a href="cache2.jsp">手动刷新</a>

 

</body>

</html>

 

cache2.jsp 执行手动刷新页面如下

<%@ taglib uri="oscache"prefix="cache" %>

 

<html>

<body>

 

缓存已刷新...<p>

 

<cache:flushkey="testcache" scope="application"/>

 

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

 

</body>

</html>

 

 

你也可以通过下面语句定义Cache的有效范围,如不定义scope,scope默认为Applcation

<cache:cache time="30"scope="session">

...

</cache:cache>

 

4. 缓存过滤器 CacheFilter

 

你可以在web.xml中定义缓存过滤器,定义特定资源的缓存。

<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>60</param-value>

</init-param>

<init-param>

<param-name>scope</param-name>

<param-value>session</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>CacheFilter</filter-name>

<url-pattern>*.jsp</url-pattern>

</filter-mapping>

上面定义将缓存所有.jsp页面,缓存刷新时间为60秒,缓存作用域为Session

 

注意,CacheFilter只捕获Http头为200的页面请求,即只对无错误请求作缓存,

而不对其他请求(如500,404,400)作缓存处理

4、有关OSCache进行缓存对象的研究

    这个是我今天要说的东西。网上对于OSCache缓存Web页面很多说明和例子,但对于缓存对象方面说得不多,我就把自已写得一些东西放出

来,让大家看一看是怎样缓存对象的!

    我基于GeneralCacheAdministrator类来写的BaseCache

   

view plainprint?

   1. packagecom.klstudio.cache;  

   2.   

   3. import java.util.Date; 

   4.   

   5. importcom.opensymphony.oscache.base.NeedsRefreshException;  

   6. import com.opensymphony.oscache.general.GeneralCacheAdministrator; 

   7.   

   8. public class BaseCacheextends GeneralCacheAdministrator {  

   9.    //过期时间(单位为秒);  

  10.    private int refreshPeriod;  

  11.     //关键字前缀字符;  

  12.    private String keyPrefix;  

  13.      

  14.    private static final long serialVersionUID = -4397192926052141162L;  

  15.      

  16.    public BaseCache(String keyPrefix,int refreshPeriod){  

 17.         super();  

 18.         this.keyPrefix = keyPrefix; 

 19.         this.refreshPeriod =refreshPeriod;  

  20.     } 

  21.     //添加被缓存的对象;  

  22.    public void put(String key,Object value){  

 23.        this.putInCache(this.keyPrefix+"_"+key,value);  

  24.     } 

  25.     //删除被缓存的对象;  

  26.     publicvoid remove(String key){  

 27.        this.flushEntry(this.keyPrefix+"_"+key);  

  28.     } 

  29.     //删除所有被缓存的对象;  

  30.    public void removeAll(Date date){  

 31.         this.flushAll(date);  

  32.     } 

  33.      

  34.    public void removeAll(){  

 35.         this.flushAll();  

  36.     } 

  37.     //获取被缓存的对象;  

  38.    public Object get(String key) throws Exception{  

 39.         try{  

 40.            return this.getFromCache(this.keyPrefix+"_"+key,this.refreshPeriod); 

 41.         } catch(NeedsRefreshException e) {  

 42.            this.cancelUpdate(this.keyPrefix+"_"+key);  

 43.            throw e;  

 44.         }  

  45.   

  46.     } 

  47.      

  48. }  

   

view plainprint?

   1. package com.klstudio; 

   2.   

   3. importcom.klstudio.News;  

   4. importcom.klstudio.cache.BaseCache;  

   5.   

   6. public classCacheManager {  

  7.       

   8.    private BaseCache newsCache;  

   9.   

  10.      

  11.    private static CacheManager instance;  

  12.    private static Object lock = new Object();  

  13.      

  14.    public CacheManager() {  

 15.         //这个根据配置文件来,初始BaseCache而已;  

 16.         newsCache = newBaseCache("news",1800);       

  17.     } 

  18.      

  19.    public static CacheManager getInstance(){  

 20.         if (instance == null){ 

 21.            synchronized( lock ){  

 22.                if (instance == null){  

 23.                    instance = new CacheManager();  

  24.                }  

 25.             } 

 26.         }  

 27.         return instance;  

  28.     } 

  29.   

  30.    public void putNews(News news) {  

 31.         // TODO 自动生成方法存根  

 32.        newsCache.put(news.getID(),news);  

  33.     } 

  34.   

  35.    public void removeNews(String newsID) {  

 36.         // TODO 自动生成方法存根  

 37.         newsCache.remove(newsID); 

  38.     } 

  39.   

  40.    public News getNews(String newsID) {  

 41.         // TODO 自动生成方法存根  

  42.        try {  

 43.            return (News) newsCache.get(newsID);  

 44.         } catch (Exception e) { 

 45.             //TODO 自动生成 catch  

 46.            System.out.println("getNews>>newsID["+newsID+"]>>"+e.getMessage()); 

 47.            News news = new News(newsID);  

 48.            this.putNews(news);  

 49.            return news;  

 50.         }  

  51.     } 

  52.   

  53.    public void removeAllNews() {  

 54.         // TODO 自动生成方法存根  

 55.         newsCache.removeAll(); 

  56.     } 

  57.   

  58. } 


猜你喜欢

转载自blog.csdn.net/qq_39313596/article/details/80549282