oscache说明设置

来源:互联网 发布:opencv分水岭算法函数 编辑:程序博客网 时间:2024/06/05 22:34

一,缓存

1.缓存对象

     直接调用API的接口即可

一、对象缓存

1、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;            }          }            }    

2、Cache管理类

public class CacheManager {            private BaseCache newsCache;                private static CacheManager instance;        private static Object lock = new Object();               private CacheManager() {            //这个根据配置文件来,初始BaseCache而已;            newsCache = new BaseCache("news",120);             }                public static CacheManager getInstance(){            if (instance == null){                synchronized( lock ){                    if (instance == null){                        instance = new CacheManager();                    }                }            }            return instance;        }           public void putUser(User news) { newsCache.put(news.getId()+"",news);      }           public void removeUser(String newsID) {  newsCache.remove(newsID);       }           public User getUser(int newsID) {            try {                return (User) newsCache.get(newsID+"");            } catch (Exception e) {                System.out.println("getNews>>newsID["+newsID+"]>>"+e.getMessage());                User news = new User(newsID);                this.putUser(news);                return news;            }        }           public void removeAllNews() {            newsCache.removeAll();        }       }

· 3、对象Bean

public class User {private int id;private String name;private String sex;private int age;private Date accessTime;public User(int id) {super();this.id = id;this.accessTime = new Date(System.currentTimeMillis());}public String toString() {return "User info is : id=" + id + "  accessTime="+ accessTime.toString();}public User(String name, String sex, int age) {super();this.name = name;this.sex = sex;this.age = age;}public User() {}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public int getId() {return id;}public void setId(int id) {this.id = id;}public Date getAccessTime() {return accessTime;}public void setAccessTime(Date accessTime) {this.accessTime = accessTime;}}

4、测试类

public class TestObjectCache {public static void main(String[] args) {CacheManager cm=CacheManager.getInstance();TestObjectCache test=new TestObjectCache();test.print(cm);}public void print(CacheManager cm){User user=null;for (int i = 0; i < 1000; i++) {user=cm.getUser(100);System.out.println("<<"+i+">>: "+user);if(i==10){//删除缓存id的对象cm.removeUser(100+"");}if(i==20){//删除所有缓存的对象cm.removeAllNews();}// 睡眠部分try {Thread.sleep(30000);} catch (Exception e) {}}}}

2、部分页面缓存

     使用OSCache提供的taglib(修改web.xml文件,在web.xml文件中增加下面的内容,增加对OSCache提供的taglib的支持:<taglib>

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

</taglib>

或者在jsp页面使用以下标签

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

3.整个页面的缓存

     用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>600</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>

[注] 只有客户访问时返回http头信息中代码为200(也就是访问已经成功)的页面信息才能够被缓存

二、配置说明

1.oscache.properties 中的配置项详解:

1)、cache.memory:

是否使用内存缓存; true 或 false。默认为true; 如设置为false,那cache只能缓存到数据库或硬盘中。

2)、cache.capacity

缓存的最大数量。默认是不限制,cache不会移走任何缓存内容。负数被视不限制。

3)、cache.algorithm

运算规则。为了使用规则,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)、cache.blocking

是否同步。true 或者 false。一般设为true,避免读取脏数据。

5)、cache.unlimited.disk

指定硬盘缓存是否要作限制。默认值为false。false的状况下,disk cache capacity 和cache.capacity的值相同。

6)、cache.persistence.class

指定类是被持久化缓存的类。class必须实现PersistenceListener接口。

作为硬盘持久,可以实现com.opensymphony.oscache.plugins.diskpersistence.HashDiskPersistenceListener接口。

它把class的toString()输出的hash值作为文件的名称。如果你要想文件名易读些(自己设定),DiskPersistenceListener 的父类也能使用,但其可能有非法字符或者过长的名字。

 注意:HashDiskPersistenceListener 和 DiskPersistenceListener 需要设定硬盘路径:cache.path

7)、cache.path

指定硬盘缓存的路径。目录如果不存在将被建立。同时注意oscache应该要有权限写文件系统。

 例:

cache.path=c:\\myapp\\cache

cache.path=/opt/myapp/cache

8)、cache.persistence.overflow.only (NEW! Since 2.1)

指定是否只有在内存不足的情况下才使用硬盘缓存。

默认值false。但推荐是true如果内存cache被允许的话。这个属性彻底的改变了cache的行为,使得persisted cache和memory是完全不同。

9)、cache.event.listeners

class名列表(用逗号隔开)。每个class必须实现以下接口中的一个 或者几个

CacheEntryEventListener:接收cache add/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 of cache map events(cache hits,misses and state hits).

10)、cache.key

在application 和 session的作用域时 用于标识cache 对象的,  用于ServletCacheAdministrator;此属性不是指定为"__oscache_cache"格式时为默认值, 如果代码中需要用到默认值时可以通使用com.opensymphony.oscache.base.Const.DEFAULT_CACHE_KEY 来取得;

11)、cache.use.host.domain.in.key

当配置多个服务器时,想通过服备器名称自动生成cache key时,可将此属性设为true. 默认值为false;

 

12)、Additional Properties

在以上基础选项之上可以加入一些额外的属性到此文件中.

例:  JavaGroupsBroadcastingListener 便是额外的.

13)、cache.cluster.multicast.ip

用于缓存集群. 默认为231.12.21.132

14)、cache.cluster.properties

指集群中的额外配置项. 以下是默认设置:(此属性的相关说将在集群文档中说明)

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)

2.jsp中的标签缓存说明

第一次请求到达时,标签中的内容被处理并且缓存起来,当下一个请求到达时,缓存系统会检查这部分内容的缓存是否已经失效,主要是以下几项:

1). 缓存时间超过了cache标签设置的time或者duration属性规定的超时时间 

2). cron属性规定的时间比缓存信息的开始时间更晚 

3). 标签中缓存的内容在缓存后又被重新刷新过 

4). 其他缓存超期设定 

如果符合上面四项中的任何一项,被缓存的内容视为已经失效,这时被缓存的内容将被重新处理并且返回处理过后的信息,如果被缓存的内容没有失效,那么返回给用户的将是缓存中的信息。 

1.cache标签的属性说明:

key   
 标识缓存内容的关键词。在指定的作用范围内必须是唯一的。默认的key是被访问页面的URI和后面的请求字符串。可以在同一个页面中使用很多cache标签而不指定他的key属性,这种情况下系统使用该页面的URI和后面的请求字符串,另外再自动给这些key增加一个索引值来区分这些缓存内容。但是不推荐采用这样的方式。   
scope   
 缓存发生作用的范围,可以是application或者session。默认为application。   
time   
 缓存内容的时间段,单位是秒,默认是3600秒,也就是一个小时,如果设定一个负值,那么这部分被缓存的内容将永远不过期。   
duration   
 指定缓存内容失效的时间,是相对time的另一个选择,可以使用简单日期格式或者符合USO-8601的日期格式。如:duration='PT5M' duration='5s'等。   
cron   
 指定缓存内容失效表达式 
Cron表达式基本语法   
        通过Cron表达式我们可以很灵活的设置缓存的失效时间,Cron表达式包括5个字段分别为Minute,Hour, DOM(Day Of Month), Month,DOW(Day Of Week)。他们顺序地对应了5个位置。当某个位置上的值为*时,表示该位置上的任意时间。另外还提供了指定时间的操作符号"-",",","/",他们分别表示一段时间范围,具体的时间,以及递增的时间段。下面是几个例子说明一下Cron表达式的基本应用:    
        (1) "10/20 * * * *" :因是第一个位置,并且是一个递增的表达式,所以表达式指定的是每个小时的第10分钟,第30分钟,第50分钟缓存内容失效。   
        (2) "* 8-18/4 * * *" :指定每天早上8点到晚上6点之间,每4个小时缓存内容失效。  等同于"* 8,12,16 * * *"。   
        (3) "* * * * 1-5":表示每个星期一到星期五内容失效。  

refresh   
 false 或者true。如果refresh属性设置为true,不管其他的属性是否符合条件,这部分被缓存的内容都将被更新,这给编程者一种选择,决定什么时候必须刷新。   
mode   
 如果不希望被缓存的内容增加到给用户的响应中,可以设置mode属性为"silent"。此时被缓存的部分不在页面上显示,而其它任意的mode属性值都会将缓存的部分显示到页面上。   
groups   
 指定当前cache标签所属的组,可使用“,”分割组名。这样就可以对缓存项进行分组了。如果缓存项依赖于应用的其它部分或其它数据,分组就有了用武之地——当这种依赖改变时(刷新相关的组),这个组的所有缓存项都将过期。   
language   
 使用ISO-639定义的语言码来发布不同的缓存内容(under an otherwise identical key)。要在一个多语言网站上同一段JSP代码不同用户的参数提供不同的语言时,这个属性会很有用。   
refreshpolicyclass   
 指定自定义的刷新策略类的全限定类名。这个类继承自com.opensymphony.oscache.web.WebEntryRefreshPolicy   
refreshpolicyparam   
 指定任意需要传给refreshpolicyclass的参数。如果没有指定refreshpolicyclass,则这个值不起作用。   
        这些属性可以单独使用,也可以根据需要组合使用。   

1.1addgroup标签   

        <addgroup />:必须嵌套在<cache>标签中。It allows groups to be dynamically added to a cached block. It is useful when the group(s) a cached block should belong to are unknown until the block is actually rendered. As each group is 'discovered', this tag can be used to add the group to the block's group list.   
        属性说明:   
group- req   
 The name of the group to add the enclosing cache block to.     
    
        示例代码如下:   
<oscache:cache key="test1">   
  
<oscache:addgroup group="group1" />   
  
... some jsp content ...   
  
<oscache:addgroup group="group2" />   
  
... some more jsp content ...   
  
</oscache:cache>   


2.flush标签   

        这个标签用于在运行时刷新缓存。只有运行flush标签后再次访问相关缓存项时才执行刷新。   
        属性说明:   
scope[all]   
 指定要刷新的范围。可选的值是"application", "session" 和 nul。null(到底是null量还是all呀)值指定刷新所有的缓存(是指使用cache标签的缓存)。   
    
key   
 当指定了scope和key值时,刷新唯一的缓存项。当这个缓存项下次被访问时将被刷新。只指定一个key值而没有指定scope不起作用。   
    
group   
 指定一个组时将刷新所有这个组中的缓存项。只指定一个group值而没有指定scope不起作用。   
    
pattern   
 任意包含pattern属性指定的值的缓存项都将被刷新。只指定一个pattern值而没有指定scope不起作用。 (注意:OSCache项目组已经不赞成使用pattern这个属性赖刷新缓存,二是鼓励使用具有更好的灵活性和性能的group属性来代替)   
    
language   
 使用ISO-639定义的语言码来发布不同的缓存内容(under an otherwise identical key)。要在一个多语言网站上同一段JSP代码不同用户的参数提供不同的语言时,这个属性会很有用。   

3.usecached标签   

        <usecached />:必须嵌套在<cache>标签中。   
        属性说明:   
use   
 告诉所在的<cache>标签是否使用已经缓存的内容(缺省为true,使用缓存的内容)。可以使用这个标签来控制缓存。比如使用<frush>标签刷新某个key的缓存,但可以在必要的地方即使这样的强制刷新也仍然使用缓存内容而不刷新。    
    
        示例代码如下:   
<oscache:cache>   
     <% try { %>   
     ... some jsp content ...   
     <% } catch (Exception e) { %>   
          <cache:usecached />   
     <% } %>   
</oscache:cache>   


0 0