OSCache

前阵子对公司网站进行了性能优化,其中,有一项就是使用OSCache添加页面的缓存,开始还不以为然,做完缓存后,发现服务器的负载大大减小了,看来还真不能小瞧OSCache。 OSCache 主要用于页面缓存,当然它也可用于数据层缓存,但数据层缓存一般使用ehcache比较成熟。OSCache对于更新较慢的页面(比如一天或半天更新一次)缓存效果比较好,能大幅降低数据库和服务器的压力,而且OSCache简单易用,是一个非常不错的缓存框架。 OSCache的配置和使用 一、oscache 环境搭建 1, 从 https://oscache.dev.java.net/files/documents/629/61427/oscache-2.4.1-full.zip 下载 oscache-2.4.1-full版本,并从压缩包中分别拷贝oscache-2.4.1.jar、oscache.properties、 oscache.tld放入本地项目的应用目录,如下: $WEB-APP"WEB-INF"lib"oscache.jar $WEB-APP"WEB-INF"classes"oscache.properties $WEB-APP"WEB-INF"classes"oscache.tld 2, 在web.xml 中加入如下配置 oscache /WEB-INF/classes/oscache.tld 3, 如果需要日志输出,可在log4j.properties文件中加入如下配置 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} 二、oscache.properties 主要配置 1,cache.memory = true 设置是否使用内存缓存 可设置为true 或者 false ,默认为true 2,cache.capacity =10000 设置缓存对象的最大数量值 默认是不限制,cache不会移走任何缓存内容,负数被当作不限制 3,cache.unlimited.disk 指定硬盘缓存是否要作限制,默认值为false false的状况下,硬盘缓存容量将和cache.capacity的值相同 4,cache.path 指定硬盘缓存的路径,目录如果不存在将被建立,同时注意oscache应该要有权限写文件系统。 设置如:cache.path=d:""myapp""cache 5,cache.persistence.overflow.only 指定是否只有在内存不足的情况下才使用硬盘缓存。默认值false,推荐使用true如果内存cache被允许的话 三、标签参数介绍 使用了oscache:cache 的属性: key 缓冲的key,可以是任何的字符串,也可以动态生成。在一个范围内必须唯一。默认使用请求的URI和请求的字符串(问号后面的部分) scope 范围,有application和session, 默认为 application time 缓冲内容的时间(秒),默认为1小时,3600秒,如果为-1则内容永远不过期 refresh 强制刷新缓存,false 或者true,可以使用此属性受动刷新需立即更新的数据 groups 设置分组,可以同组的缓冲数据进行控制 language 语言,默认为当前页面的语言 还有许多其他的属性,在这里不一一列举 四、oscache 基本用法 1,设置缓存

被缓存的列表 其中,cacheKey和time可以自己动态构件,scope(缓存范围) 可以是ession、application 注意:cacheKey或者time如果是jsp表达式时,如:key=”

”而不是:key=”string

”,写法要注意,否则页面会报错 2,刷新缓存

3,分组缓存 这里面的内容被缓存到键值为cacheKey_1,组名为a和b的缓存中,正常情况下,每隔5秒钟刷新一 次,但受上面标签“”的影响,它将随每次页面的刷新而刷新 这里面的内容被缓存到键值为cacheKey_2,组名为a的缓存中,它将每隔5秒中刷新一次 这里面的内容被缓存到cacheKey_3,组a,b中,组是通过标签而添加的,它也会受本页开头标签“”的影响而随页面刷新而刷新 这里面的内容被缓存到cacheKey_4,组a,b中,组是通过标签而添加的,它也会受本页开头标签“”的影响而随页面刷新而刷新 五、参考资料 1,oscache-2.4.1-full 中的demo,下在地址: https://oscache.dev.java.net/files/documents/629/61427/oscache-2.4.1-full.zip 2,oscache API:http://www.opensymphony.com/oscache/api/

 

=========================================================================

下面简单介绍一下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包。
如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.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>

2.为了便于调试日志输出,须加入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

3.hibernate-session配置
   <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mappingResources">
            <list>
                <value>com/ouou/album/model/Albums.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.cglib.use_reflection_optimizer">false</prop>
                <!--<prop key="hibernate.query.substitutions">true 'Y', false 'N'</prop>-->
                <prop key="hibernate.query.substitutions">true 1, false 0</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>                                              <prop key="hibernate.cache.provider_class">com.opensymphony.oscache.hibernate.OSCacheProvider
                 </prop>
                <prop key="hibernate.show_sql">true</prop>
                <!--<prop key="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop> -->
                <prop key="hibernate.jdbc.batch_size">25</prop>
            </props>
        </property>
    </bean>

4.oscache.properties 文件配置向导
cache.memory
值为true 或 false ,默认为在内存中作缓存,
如设置为false,那cache只能缓存到数据库或硬盘中,那cache还有什么意义:)
cache.persistence.class
持久化缓存类,如此类打开,则必须设置cache.path信息
cache.capacity
缓存元素个数
cache.cluster 相关
为集群设置信息。

cache.cluster.multicast.ip为广播IP地址
cache.cluster.properties为集群属性

配置例子:
cache.memory=true
cache.key=__oscache_cache
cache.path=/data/oscache
cache.capacity=100000
cache.unlimited.disk=true

5.OSCache的基本用法

cache1.jsp 内容如下
<%@ 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>

6. 缓存过滤器 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)作缓存处理
  
7.关于oscache的几个基础方法:
  public abstract class BaseManager<T extends BaseObject> implements Manager<T> ...{

    private static Log logger = LogFactory.getLog(BaseManager.class);
  
    private Cache oscache;
    public Cache getOscache() ...{
        return oscache;
    }
    public void setOscache(Cache oscache) ...{
        this.oscache = oscache;
    }
    protected final String createCachekey(Object keyParams[]) ...{
        if (keyParams == null) ...{
            return "";
        }

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < (keyParams.length - 1); i++) ...{
            sb.append(keyParams[i].toString()).append("':'");
        }

        return sb.append(keyParams[keyParams.length - 1]).toString();
    }

    public Object getCacheValue(String key) ...{
        return getCacheValue(key, null);
    }

    public Object getCacheValue(String key, Object obj) ...{
        Object new_obj = null;

        try ...{
            new_obj = oscache.getFromCache(key);
        } catch (NeedsRefreshException nre) ...{
            oscache.cancelUpdate(key);

            if (logger.isWarnEnabled()) ...{
                logger.warn("Failed to get from Cache");
            }
        }

        return (new_obj != null) ? new_obj : obj;
    }

    public void setCache(String key, Object serial) ...{
        setCache(key, serial, default_cache_time_second);
    }

    public void setCache(String key, Object serial, int cache_time) ...{
        if (oscache != null) ...{
            oscache.putInCache(key, serial, new ExpiresRefreshPolicy(cache_time));
        }
    }

    public void delCache(String key) ...{
        if (oscache != null) ...{
            oscache.removeEntry(key);
        }
    }

    public void flushCache(String key) ...{
        if (oscache != null) ...{
            oscache.flushEntry(key);
        }
    }
 }

OSCache是什么? OSCache标记库由OpenSymphony设计,它是一种开创性的缓存方案,它提供了在现有JSP页面之内实现内存缓存的功能。OSCache是个一个被广泛采用的高性能的J2EE缓存框架,OSCache还能应用于任何Java应用程序的普通的缓存解决方案。 2、OSCache的特点 (1) 缓存任何对象:你可以不受限制的缓存部分jsp页面或HTTP请求,任何java对象都可以缓存。 (2) 拥有全面的API:OSCache API允许你通过编程的方式来控制所有的OSCache特性。 (3) 永久缓存:缓存能被配置写入硬盘,因此允许在应用服务器的多次生命周期间缓存创建开销昂贵的数据。 (4) 支持集群:集群缓存数据能被单个的进行参数配置,不需要修改代码。 (5) 缓存过期:你可以有最大限度的控制缓存对象的过期,包括可插入式的刷新策略(如果默认性能不能满足需要时)。 3、OSCache的安装与配置 网上已经有一个不错的使用教程:http://blog.csdn.net/ezerg/archive/2004/10/14/135769.aspx 4、有关“用OSCache进行缓存对象”的研究 这个是我今天要说的东西。网上对于OSCache缓存Web页面很多说明和例子,但对于缓存对象方面说得不多,我就把自已写得一些东西放出来,让大家看一看是怎样缓存对象的! 我基于GeneralCacheAdministrator类来写的BaseCache类 view plaincopy to clipboardprint?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.cache;<br/><br/>import java.util.Date;<br/><br/>import com.opensymphony.oscache.base.NeedsRefreshException;<br/>import com.opensymphony.oscache.general.GeneralCacheAdministrator;<br/><br/>public class BaseCache extends GeneralCacheAdministrator {<br/> //过期时间(单位为秒);<br/> private int refreshPeriod;<br/> //关键字前缀字符;<br/> private String keyPrefix;<br/> <br/> private static final long serialVersionUID = -4397192926052141162L;<br/> <br/> public BaseCache(String keyPrefix,int refreshPeriod){<br/> super();<br/> this.keyPrefix = keyPrefix;<br/> this.refreshPeriod = refreshPeriod;<br/> }<br/> //添加被缓存的对象;<br/> public void put(String key,Object value){<br/> this.putInCache(this.keyPrefix+"_"+key,value);<br/> }<br/> //删除被缓存的对象;<br/> public void remove(String key){<br/> this.flushEntry(this.keyPrefix+"_"+key);<br/> }<br/> //删除所有被缓存的对象;<br/> public void removeAll(Date date){<br/> this.flushAll(date);<br/> }<br/> <br/> public void removeAll(){<br/> this.flushAll();<br/> }<br/> //获取被缓存的对象;<br/> public Object get(String key) throws Exception{<br/> try{<br/> return this.getFromCache(this.keyPrefix+"_"+key,this.refreshPeriod);<br/> } catch (NeedsRefreshException e) {<br/> this.cancelUpdate(this.keyPrefix+"_"+key);<br/> throw e;<br/> }<br/><br/> }<br/> <br/>}<br/><br/><br/> 通过CacheManager类来看怎样缓存对象的,这个类中所用的News只是具体功能的类,我就不贴出来了,你可以自己写一个! view plaincopy to clipboardprint?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(); } } package com.klstudio;<br/><br/>import com.klstudio.News;<br/>import com.klstudio.cache.BaseCache;<br/><br/>public class CacheManager {<br/> <br/> private BaseCache newsCache;<br/><br/> <br/> private static CacheManager instance;<br/> private static Object lock = new Object();<br/> <br/> public CacheManager() {<br/> //这个根据配置文件来,初始BaseCache而已;<br/> newsCache = new BaseCache("news",1800); <br/> }<br/> <br/> public static CacheManager getInstance(){<br/> if (instance == null){<br/> synchronized( lock ){<br/> if (instance == null){<br/> instance = new CacheManager();<br/> }<br/> }<br/> }<br/> return instance;<br/> }<br/><br/> public void putNews(News news) {<br/> // TODO 自动生成方法存根<br/> newsCache.put(news.getID(),news);<br/> }<br/><br/> public void removeNews(String newsID) {<br/> // TODO 自动生成方法存根<br/> newsCache.remove(newsID);<br/> }<br/><br/> public News getNews(String newsID) {<br/> // TODO 自动生成方法存根<br/> try {<br/> return (News) newsCache.get(newsID);<br/> } catch (Exception e) {<br/> // TODO 自动生成 catch 块<br/> System.out.println("getNews>>newsID["+newsID+"]>>"+e.getMessage());<br/> News news = new News(newsID);<br/> this.putNews(news);<br/> return news;<br/> }<br/> }<br/><br/> public void removeAllNews() {<br/> // TODO 自动生成方法存根<br/> newsCache.removeAll();<br/> }<br/><br/>}<br/><br/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值