如何在程序中加入缓存机制

看别人写的源程序,发现使用了缓存处理机制,好奇,学习了一下,很有意思的东西。
它使用的是whirlycache这一个开源项目,版本0.7.老了点。先用着。
//定义自己的缓存类
public class MemberCache {
//这里是默认的缓存时间
public static final long TIME_OUT = DateUtil.HOUR;
private static Log log = LogFactory.getLog(MemberCache.class);
//创建一个单例
static private MemberCache instance = new MemberCache();
//真正的缓存对象,你缓存的东西全存在里面了
private Cache cache;
//构造函数
public MemberCache() {
try {
//初始化缓存对象
cache = CacheManager.getInstance().getCache("member");
} catch (CacheException ex) {
log.error("Cannot get the WhirlyCache. Member caching is disabled.", ex);
} catch (LinkageError e) {
// @todo: Should be never throw
log.error("Cannot get the WhirlyCache caused by Package Conflict. Member caching is disabled.", e);
}
}
static public MemberCache getInstance() {
return instance;
}
public String getEfficiencyReport() {
String result = "No report";
if (cache == null) {
if (MVNForumConfig.getEnableCacheMember() == false) {
result = "Cache is disabled.";
} else {
result = "Cache cannot be inited";
}
} else if (cache instanceof CacheDecorator) {
result = ((CacheDecorator)cache).getEfficiencyReport();
}
return result;
}
public void clear() {
if (cache != null) {
cache.clear();
}
}
//这里存储并读取缓存一个用户总数信息
public long getMemberTotalCount() throws ObjectNotFoundException, AssertionException, DatabaseException{
longcount = 0;
if (cache != null) {
//这里是键值
String key = new String("getMemberTotalCount");
//根据键值获取对象,这里原来是一个Long,但是存不进去,换成String就可以了
String Scount = (String)cache.retrieve(key);
//如果缓存中不存在
if (Scount == null) {
//从非缓存中读取
Scount= = String.valueOf(DAOFactory.getMemberDAO().getNumberOfMembers());
//存入缓存
cache.store(key, Scount, DateUtil.MINUTE);
log.info("缓存中不存在,创建后存入");
}else{
count=new Long(Scount);
log.info("从缓存中读取会员总数成功");
}
} else {
//当前缓存未启用,从数据库中直接读取
count = new Long(DAOFactory.getMemberDAO().getNumberOfMembers());
}
}
}
很简单吧。

你可能感兴趣的:(cache)