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

 
看别人写的源程序,发现使用了缓存处理机制,好奇,学习了一下,很有意思的东西。
它使用的是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{
           long count = 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());
        }
 
     
    }
 
}
很简单吧。
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值