Web开发过程中,我们经常会碰到缓存的问题,缓存的合理使用可以使网站性能有大幅度提高(当然需要高的命中率),我这里只是抛砖引玉一下,用OSCache开源框架来实现缓存,缓存一般可以用在网站的首页数据缓存(不需要很实时的数据,如类似一些排行数据啊,热门数据啊什么的),还可以用在报表(一般报表都在一定的时间内才触发更改的),还可以用在类似的诸多场合,我这里不再累赘,使用OSCache可以给你带来很多好处,它可以缓存JSP页面(并且提供了tld文件),你可以使用标签,还可以使用Java代码中的数据缓存,对象缓存等,好处多多,废话少说,OSCache API我也是刚刚才接触,还是比较简单明了的,官方网站API:http://www.opensymphony.com/oscache/api/ ,使用文档:http://wiki.opensymphony.com/display/CACHE/Documentation ,例子代码你可以下载OSCache Full版,里面有很多Junit的测试用例,初步想了一下,可以这样实现代码:
定义一个缓存所需要用的标识接口
Java代码
publicinterfaceIOSCachable(){}
public interface IOSCachable(){}
定义一个缓存操作类
Java代码
GeneralCacheAdministrator admin;
publicOSCache(){
admin =newGeneralCacheAdministrator();
}
publicOSCache(intsize) {
admin =newGeneralCacheAdministrator();
admin.setCacheCapacity(size);
}
publicvoidput(String key, String value) {
this.admin.putInCache(key,value);
}
publicvoidput(String key,IOSCachable obj){
this.admin.putInCache(key,obj);
}
publicvoidput(String key,String value,String[] groups){
this.admin.putInCache(key,value,groups);
}
publicvoidput(String key,IOSCachable obj,String[] groups){
this.admin.putInCache(key,obj,groups);
}
publicIOSCachable get(String key,String defaultValue,intmyRefreshPeriod){
try{
return(IOSCachable)this.admin.getFromCache(key,myRefreshPeriod);
}catch(NeedsRefreshException ex){
this.admin.putInCache(key, defaultValue);
returnnull;
}
}
publicIOSCachable get(String key,String defaultValue){
try{
return(IOSCachable)this.admin.getFromCache(key);
}catch(NeedsRefreshException ex){
this.admin.putInCache(key, defaultValue);
returnnull;
}
}
GeneralCacheAdministrator admin;
public OSCache(){
admin = new GeneralCacheAdministrator();
}
public OSCache(int size) {
admin = new GeneralCacheAdministrator();
admin.setCacheCapacity(size);
}
public void put(String key, String value) {
this.admin.putInCache(key,value);
}
public void put(String key,IOSCachable obj){
this.admin.putInCache(key,obj);
}
public void put(String key,String value,String[] groups){
this.admin.putInCache(key,value,groups);
}
public void put(String key,IOSCachable obj,String[] groups){
this.admin.putInCache(key,obj,groups);
}
public IOSCachable get(String key,String defaultValue,int myRefreshPeriod){
try{
return (IOSCachable)this.admin.getFromCache(key,myRefreshPeriod);
}catch(NeedsRefreshException ex){
this.admin.putInCache(key, defaultValue);
return null;
}
}
public IOSCachable get(String key,String defaultValue){
try{
return (IOSCachable)this.admin.getFromCache(key);
}catch(NeedsRefreshException ex){
this.admin.putInCache(key, defaultValue);
return null;
}
}
开始使用吧
通过put,get缓存对象开始使用