一,缓存
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标签的属性说明:
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>