OSCache缓存框架学习

来源:互联网 发布:开贝抠图软件 编辑:程序博客网 时间:2024/05/16 16:01

OSCache简介:

    OSCache是个一个广泛采用的高性能的J2EE缓存框架,提供了在现有JSP页面之内实现快速内存缓冲的功能。主要流行用于jsp页面缓存,其实数据缓存也行,自己实现下就行了(本文后面会有介绍)。

 

-特点:

Oscache提供了可定制了缓存策略,你可以通过oscache标签 定制自己的缓存数据,比如一个jsp页面,或是某个jsp页面中的某快div数据,抑或通过CacheFilter来缓存所有jsp页面数据等等;

 

-使用:

   1-新建Web Project :OSCacheTest

     

   2-下载oscache-2.3.1-full 包,解压出来->将oscache-2.3.1.jar 和commons-logging.jar 两个包 部署到web项目的lib目录下;

   3-将oscache-2.3.1-full 包中oscache.properties 和 oscache.tld 拷贝到 src目录下;

  4-修改并配置oscache.properties 属性文件,oscache.tld 暂不需要配置

     -oscache.properties属性文件说明:

4-1cache.memory
原文:
   Valid values are true or false, with true being the default value.If you want to disable memory caching,just comment out or remove this line.
   Note: disabling memory AND disk caching is possible but fairlystupid
译文:
   是否使用内存缓存; true 或 false。默认为true;
   个人推荐内存方法,在速度会有些优势;
4-2cache.capacity
原文:
   The maximum number of items that a cache will hold. By default thecapacity is unlimited - the cache will never remove any items.Negative valueswill also be treated as meaning unlimited capacity.
译文:
   缓存的最大数量。默认是不限制,cache不会移走任何缓存内容。负数被视不限制。
4-3cache.algorithm
原文:
   The default cache algorithm to use. Note that in order to use analgorithm the cache size must also be specified.
   If the cache size is not specified, the cache algorithm will beUnlimited cache regardless of the value of this property. If you specify a sizebut not an algorithm, the cache algorithm used will becom.opensymphony.oscache.base.algorithm.LRUCache.
OSCache currently comes with three algorithms:
   * com.opensymphony.oscache.base.algorithm.LRUCache - LeastRecently Used.
        This is the default when a cache.capacity is set.
   * com.opensymphony.oscache.base.algorithm.FIFOCache - First InFirst Out.
   * com.opensymphony.oscache.base.algorithm.UnlimitedCache - Contentthat is added to the cache will never be discarded.
   This is the default when no value is set for the cache.capacityproperty.
译文:
   运算规则。为了使用规则,cache的size必须是指定的。
   如果cache的size不指定的话, 将不会限制缓存对象的大小。如果指定了cache的size,但不指定algorithm,
   那它会默认使用:com.opensymphony.oscache.base.algorithm.LRUCache
   有下面三种规则:
   *com.opensymphony.oscache.base.algorithm.LRUCache      : last in first out(最后插入的最先调用)。默认选项。
   * com.opensymphony.oscache.base.algorithm.FIFOCache     : first int first out(最先插入的最先调用)。
   * com.opensymphony.oscache.base.algorithm.UnlimitedCache : cache中的内容将永远不会被丢弃。
   如果cache.capacity不指定值的话,它将被设为默认选项。
4-4cache.blocking
原文:
   When a request is made for a stale cache entry, it is possiblethat another thread is already in the process of rebuilding that entry. Thissetting specifies how OSCache handles the subsequent 'non-building' threads.The default behaviour
(cache.blocking=false) is to serve the old content to subsequent threads untilthe cache entry has been updated.
   This provides the best performance (at the cost of servingslightly stale data). When blocking is enabled,threads will instead block untilthe new cache entry is ready to be served. Once the new entry is put in thecache the blocked threads will be restarted and given the new entry.
   Note that even if blocking is disabled, when there is no staledata available to be served threads will block until the data is added to thecache by the thread that is responsible for building the data.
译文:
   是否同步。true 或者 false。一般设为true,避免读取脏数据。
4-5cache.unlimited.disk
原文:
   Indicates whether the disk cache should be treated as unlimited ornot. The default value is false.In this case, the disk cache capacity will beequal to the memory cache capacity set by cache.capacity.
译文:
   指定硬盘缓存是否要作限制。默认值为false。false的状况下,disk cache capacity 和cache.capacity的值相同。
4-6cache.persistence.class
原文:
   Specifies the class to use for persisting cache entries. Thisclass must implement the PersistenceListener interface.
   OSCache comes with an implementation that provides filesystembased persistence.
Set this property tocom.opensymphony.oscache.plugins.diskpersistence.HashDiskPersistenceListener toenable this implementation.By specifying your own class here you should be ableto persist cache data using say JDBC or LDAP.
   NOTE: This class hashes the toString() of the object being cachedto produce the file name of the entry.If you prefer readable file names, theparent DiskPersistenceListener can still be used but it will have issues withillegalfilesystem characters or long names.The HashDiskPersistenceListener andDiskPersistenceListener classes require cache.path to be set in order to knowwhere to persist the files to disk.
译文:
   指定类是被持久化缓存的类。class必须实现PersistenceListener接口。作为硬盘持久,可以实现com.opensymphony.oscache.plugins.diskpersistence.HashDiskPersistenceListener 接口。
它把class的toString()输出的hash值作为文件的名称。如果你要想文件名易读些(自己设定),DiskPersistenceListener 的父类也能使用,但其可能有非法字符或者过长的名字。
注意:
   HashDiskPersistenceListener 和 DiskPersistenceListener需要设定硬盘路径:cache.path
4-7cache.path
原文:
   This specifies the directory on disk where the caches will bestored. The directory will be created if it doesn't already exist,
   but remember that OSCache must have permission to write to this location.Avoid sharing the same cache path between different caches, because OSCache hasnot been designed to handle this.
   Note:For Windows machines, the backslash character '\' needs to beescaped. ie in Windows:
      cache.path=c:\\myapp\\cache
   or *ix:
      cache.path=/opt/myapp/cache
译文:
   指定硬盘缓存的路径。目录如果不存在将被建立。同时注意oscache应该要有权限写文件系统。
   例:
     cache.path=c:\\myapp\\cache
   or *ix:
     cache.path=/opt/myapp/cache
4-8cache.persistence.overflow.only (NEW! Since 2.1)
原文:
   Indicates whether the persistence should only happen once thememory cache capacity has been reached.
   The default value is false for backwards compatibility but therecommended value is true when the memory cache is enabled.
   This property drastically changes the behavior of the cache inthat the persisted cache will now be different then what is in memory.
译文:
   指定是否只有在内存不足的情况下才使用硬盘缓存。
   默认值false。但推荐是true如果内存cache被允许的话。这个属性彻底的改变了cache的行为,使得persisted cache和memory是完全不同。
4-9cache.event.listeners
    原文:

       This takes a comma-delimited list offully-qualified class names. Each class in the list must implement one (ormore) of
       the following interfaces:
           *CacheEntryEventListener - Receives cache add/update/flush and remove events.
           * CacheMapAccessEventListener- Receives cache access events. This allows you to keep statistical informationto track
             howeffectively the cache is working.
       No listeners are configured by default,however some ship with OSCache that you may wish to enable:
          *com.opensymphony.oscache.plugins.clustersupport.BroadcastingCacheEventListener- provides clustering support for OSCache.
            Enabling this will cause cache flush events to be broadcast to other instancesof OSCache running on your LAN.
             SeeClustering OSCache for further information about this event listener.
           *com.opensymphony.oscache.extra.CacheEntryEventListenerImpl - a simple listenerimplementation that maintains a running
             countof all of the entry events that occur during a cache's lifetime.
           *com.opensymphony.oscache.extra.CacheMapAccessEventListenerImpl - a simplelistener implementation that keeps count of
             allthe cache map events (cache hits and misses, and stale hits) that occur on acache instance.
    译文:
       class名列表(用逗号隔开)。每个class必须实现以下接口中的一个 或者几个
       CacheEntryEventListener:接收cacheadd/update/flush and remove事件
       CacheMapAccessEventListener :接收cache访问事件。这个可以让你跟踪cache怎么工作。
       默认是不配置任何class的。当然你可以使用一下的class:
           *com.opensymphony.oscache.plugins.clustersupport.BroadcastingCacheEventListener: 分布式的监听器。可以广播到局域网内的其他cache实例。
            *com.opensymphony.oscache.extra.CacheEntryEventListenerImpl :一个简单的监听器。在cache的生命周期中记录所有entry的事件。
            *com.opensymphony.oscache.extra.CacheMapAccessEventListenerImpl : 记录count ofcache map events(cache hits,misses and state hits).
4-10、cache.key
    原文:
       This is the key that will be used by theServletCacheAdministrator
       (and hence the custom tags) to store thecache object in the application and session scope.
       The default value when this property isnot specified is "__oscache_cache". If you want to access thisdefault value in your code,
       it is available as com.opensymphony.oscache.base.Const.DEFAULT_CACHE_KEY.
    译文:
        在application 和 session的作用域时 用于标识cache 对象的,  用于ServletCacheAdministrator;
        此属性不是指定为"__oscache_cache"格式时为默认值, 如果代码中需要用到默认值时可以通使用com.opensymphony.oscache.base.Const.DEFAULT_CACHE_KEY
来取得;
4-11、cache.use.host.domain.in.key
    原文:
        If your server is configured withmultiple hosts, you may wish to add host name information to automaticallygenerated
       cache keys. If so, set this property totrue. The default value is false.
    译文:
        当配置多个服务器时,想通过服备器名称自动生成cachekey时,可将此属性设为true. 默认值为false;
     
4-12、AdditionalProperties
    原文:
        In additon to the above basicoptions, any other properties that are specified in this file will still beloaded and can be
       made available to your event handlers. Forexample, the JavaGroupsBroadcastingListener supports the following additional
      properties:
    译文:
        在以上基础选项之上可以加入一些额外的属性到此文件中.
       例: JavaGroupsBroadcastingListener 便是额外的.
4-13、cache.cluster.multicast.ip
    原文:
        The multicast IP to use for thiscache cluster. Defaults to 231.12.21.132.
    译文:
        用于缓存集群. 默认为231.12.21.132
4-14、cache.cluster.properties
   原文:
        Specifies additional configurationoptions for the clustering. The default setting is
      UDP(mcast_addr=231.12.21.132;mcast_port=45566;ip_ttl=32;\
      mcast_send_buf_size=150000;mcast_recv_buf_size=80000):\
       PING(timeout=2000;num_initial_members=3):\
      MERGE2(min_interval=5000;max_interval=10000):\
       FD_SOCK:VERIFY_SUSPECT(timeout=1500):\
      pbcast.NAKACK(gc_lag=50;retransmit_timeout=300,600,1200,2400,4800;max_xmit_size=8192):\
       UNICAST(timeout=300,600,1200,2400):\
       pbcast.STABLE(desired_avg_gossip=20000):\
       FRAG(frag_size=8096;down_thread=false;up_thread=false):\
      pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;shun=false;print_local_addr=true)
    译文:
        指集群中的额外配置项. 以下是默认设置:(此属性的相关说将在集群文档中说明)
      UDP(mcast_addr=231.12.21.132;mcast_port=45566;ip_ttl=32;\
       mcast_send_buf_size=150000;mcast_recv_buf_size=80000):\
       PING(timeout=2000;num_initial_members=3):\

      MERGE2(min_interval=5000;max_interval=10000):\
       FD_SOCK:VERIFY_SUSPECT(timeout=1500):\
      pbcast.NAKACK(gc_lag=50;retransmit_timeout=300,600,1200,2400,4800;max_xmit_size=8192):\
       UNICAST(timeout=300,600,1200,2400):\
       pbcast.STABLE(desired_avg_gossip=20000):\
      FRAG(frag_size=8096;down_thread=false;up_thread=false):\
     pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;shun=false;print_local_addr=true)
原文:
    See the Clustering OSCache documentation for further detailson the above two properties.
译文:
   以上两项的详细信息可以看 OSCache集群文档(http://wiki.opensymphony.com/display/CACHE/Clustering);
OSCache 的分布式缓存效果不佳, 所以最终决定不再继续研究下去.  同时转向ehCache 的研究(文档正在整理当中);

 

5-缓存数据(对象)

 5.1-创建实体类 User:

package com.bbc.bean;

 

import java.io.Serializable;

 

public class User implements Serializable {

       privateint id;

       privateString name;

       privateint age;

       privateString detail;

 

       public intgetId() {

              returnid;

       }

 

       publicvoid setId(int id) {

              this.id= id;

       }

 

       publicString getName() {

              returnname;

       }

 

       publicvoid setName(String name) {

              this.name= name;

       }

 

       public intgetAge() {

              returnage;

       }

 

       publicvoid setAge(int age) {

              this.age= age;

       }

 

       publicString getDetail() {

              returndetail;

       }

 

       publicvoid setDetail(String detail) {

              this.detail= detail;

       }

 

       @Override

       public inthashCode() {

              finalint prime = 31;

              intresult = 1;

              result= prime * result + age;

              result= prime * result + ((detail == null) ? 0 : detail.hashCode());

              result= prime * result + id;

              result= prime * result + ((name == null) ? 0 : name.hashCode());

              returnresult;

       }

 

       @Override

       publicboolean equals(Object obj) {

              if(this == obj)

                     returntrue;

              if(obj == null)

                     returnfalse;

              if(getClass() != obj.getClass())

                     returnfalse;

              Userother = (User) obj;

              if(age != other.age)

                     returnfalse;

              if(detail == null) {

                     if(other.detail != null)

                            returnfalse;

              }else if (!detail.equals(other.detail))

                     returnfalse;

              if(id != other.id)

                     returnfalse;

              if(name == null) {

                     if(other.name != null)

                            returnfalse;

              }else if (!name.equals(other.name))

                     returnfalse;

              returntrue;

       }

 

       @Override

       publicString toString() {

              return"User [age=" + age + ", detail=" + detail + ",id=" + id

                            +", name=" + name + "]";

       }

 

}

 

5.2-创建缓存工具类-BaseCache 继承GeneralCacheAdministrator重写类中的方法,GeneralCacheAdministrator类 提供了一系列的操纵缓存对象的方法,重写或者直接调用即可:

官方文档中GeneralCacheAdministrator的方法:

Method Summary

 void

cancelUpdate(String key) 
          Cancels a pending cache update.

 void

destroy() 
          Shuts down the cache administrator.

 void

flushAll() 
          Flush the entire cache immediately.

 void

flushAll(Date date) 
          Flush the entire cache at the given date.

 void

flushEntry(String key) 
          Flushes a single cache entry.

 void

flushGroup(String group) 
          Flushes all items that belong to the specified group.

 void

flushPattern(String pattern) 
          Deprecated. For performance and flexibility reasons it is preferable to store cache entries in groups and use the
flushGroup(String) method instead of relying on pattern flushing.

 Cache

getCache() 
          Grabs a cache

 Object

getFromCache(String key) 
          Get an object from the cache

 Object

getFromCache(String key, int refreshPeriod) 
          Get an object from the cache

 Object

getFromCache(String key, int refreshPeriod, String cronExpression) 
          Get an object from the cache

 void

putInCache(String key, Object content) 
          Put an object in a cache

 void

putInCache(String key, Object content, EntryRefreshPolicy policy) 
          Put an object in a cache

 void

putInCache(String key, Object content, String[] groups) 
          Puts an object in a cache

 void

putInCache(String key, Object content, String[] groups, EntryRefreshPolicy policy) 
          Puts an object in a cache

 void

removeEntry(String key) 
          Remove an object from the cache

 void

setCacheCapacity(int capacity) 
          Sets the cache capacity (number of items).

 

package com.bbc.base;

 

import com.opensymphony.oscache.base.NeedsRefreshException;

import com.opensymphony.oscache.general.GeneralCacheAdministrator;

 

public class BaseCache extends GeneralCacheAdministrator {

 

    public void put(String key,Object value) {

       this.putInCache(key, value);

    }

 

    public Object get(String key)throws NeedsRefreshException {

       return this.getFromCache(key);

    }

 

    public void delete(String key) {

       this.removeEntry(key);

    }

 

}

 

5.3-进行测试:

package com.bbc.test;

 

import org.junit.Test;

 

import com.bbc.base.BaseCache;

import com.bbc.bean.User;

import com.opensymphony.oscache.base.NeedsRefreshException;

 

public class MyTest {

 

    @Test

    public void test1() {

       User user = new User();

       user.setAge(12);

       user.setDetail("是个好孩子呢");

       user.setName("luxury");

       user.setId(1);

       BaseCache cache = newBaseCache();

       cache.put(1 + "",user);

       System.out.println("------------------");

       for (int i = 0; i < 2; i++){

           try {

              User u1 = (User)cache.get(1 + "");

              System.out.println("从缓存中 取出数据 u1: " + u1.toString());

              System.out.println("---------------");

 

              User u2 = (User)cache.get(2 + "");

              if (u2 != null) {

                  System.out.println("从缓存中 取出数据 u2: " + u2.toString());

              }

           } catch(NeedsRefreshException e) {

              System.out.println("缓存中没有数据!!!");

              User u2 = new User();

              u2.setId(2);

              u2.setAge(13);

              u2.setDetail("哈哈 我是小孩子");

              u2.setName("xiaohong");

              cache.put(2 +"", u2);

              System.out.println("从数据库取出数据-u2,并 放入了 缓存中...");

           }

 

       }

 

    }

 

}

运行结果-

2014-11-14 13:31:25 com.opensymphony.oscache.base.Config loadProps

信息: Properties {cache.blocking=true, cache.capacity=1000,cache.memory=true}

2014-11-14 13:31:25 com.opensymphony.oscache.general.GeneralCacheAdministrator<init>

信息: Constructed GeneralCacheAdministrator()

2014-11-14 13:31:25com.opensymphony.oscache.general.GeneralCacheAdministrator createCache

信息: Creating new cache

------------------

从缓存中 取出数据 u1: User [age=12, detail=是个好孩子呢, id=1,name=luxury]

---------------

缓存中没有数据!!!

从数据库取出数据-u2,并 放入了 缓存中...

从缓存中 取出数据 u1: User [age=12, detail=是个好孩子呢, id=1,name=luxury]

---------------

从缓存中 取出数据 u2: User [age=13, detail=哈哈 我是小孩子, id=2,name=xiao hong]

 

6-jsp页面缓存:

上面的部署配置 是对数据(对象)的缓存,想要在应用中对jsp页面内容进行缓存的话,还要再进行其他配置:

Jsp缓存的实现有两种方式,其一:自己定制缓存内容,采用oscache标签来定制要缓存的某个jsp内容;其二:在web.xml中进行全局配置,使用CacheFilter控制所有jsp或单个jsp页面缓存;

6.1-oscache标签方式 实现:

  这个在oscache-2.3.1.jar包中src 目录下 有官方提供的更详细测试案例:

  因为要使用oscache标签,首先要声明注册这个标签,在web.xml中进行添加配置:

    <taglib>

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

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

       </taglib>

 

[hello1.jsp----]

<%@ page language="java" contentType="text/html;charset=utf-8"

   pageEncoding="utf-8"%>

<%@page import="java.util.*"%>

       <%@pageimport="java.text.SimpleDateFormat"%>   

<%@ taglib uri="/WEB-INF/classes/oscache.tld"prefix="oscache"%>

 <%

int sessionid=(Integer)request.getSession().hashCode();

 %> 

<html>

<head>

<title>OSCache Test </title>

</head>

    <body>

 

<br/>

sessionID=<%=sessionid%>

            没有缓存的日期:

             <%Date currentTime =new Date();

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");

String dateString = formatter.format(currentTime);

        %>

 

         <td><%=dateString%></td>

            <br>

            <!--自动刷新-->

            <oscache:cachetime="5" refresh="true">

                每5秒刷新缓存一次的日期:  <%Date currentTime1 = new Date();

SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");

String dateString1 = formatter1.format(currentTime1);

   %>

 

         <td><%=dateString1%></td>

            </oscache:cache>

            <br>

            <!--手动刷新-->

            <oscache:cachekey="testcache">

                手动刷新缓存的日期: <%Date currentTime2 = new Date();

SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");

String dateString2 = formatter2.format(currentTime2);

   %>

 

         <td><%=dateString2%></td>

            </oscache:cache>

            <br>

            <ahref="hello2.jsp">手动刷新</a>

    </body>

</html>

[hello2.jsp----]

<%@ page language="java" contentType="text/html;charset=gbk"

   pageEncoding="gbk"%>

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

       <%@page import="java.text.SimpleDateFormat"%>

<%@ taglib uri="/WEB-INF/classes/oscache.tld"prefix="oscache"%>

 

<html>

<body>

 

缓存已刷新...<p>

 

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

 

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

 

</body>

</html>

 

 

6.2-CacheFilter方式 实现:

在web.xml中配置CacheFilter

 

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5"xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 

 

    <!--整个页面的缓存:用CashFilter实现页面级缓存,可缓存单个文件、缓存URL pattern和自己设定缓存属性的缓存。  -->

<!---->

    <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>5</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>

 

      

           对所有jsp页面进行缓存<url-pattern>*.jsp</url-pattern> </filter-mapping>

      

       <!--

           对指定jsp页面进行缓存<url-pattern>/hello1.jsp</url-pattern> </filter-mapping>

       -->

 

       <welcome-file-list>

           <welcome-file>index.jsp</welcome-file>

       </welcome-file-list>

</web-app>

 

这样的话,所有访问到的且成功(Status==200)的jsp页面都会被OSCache缓存;

 

 

配置文件-参考:

http://blog.chinaunix.net/uid-122937-id-142910.html

0 0
原创粉丝点击