Cache2j:进阶之Stats讲解

Stats用来统计缓存命中情况,包括命中数量hitCount,未命中数量missCount及重新加载的次数reloadCount.

/**
 * 缓存统计信息,含命中次数,未命中次数及命中率。
 * @author zxm
 * @since 2018.02.01
 */
public final class Stats {
    private AtomicLong hitCount = new AtomicLong();
    private AtomicLong missCount = new AtomicLong();
    private AtomicLong reloadCount = new AtomicLong();
    ...
}

具体使用时可以通过CacheBuilder开启,

public CacheBuilder<K,V> stats(){
        this.stats = new Stats();
        return this;
    }

开启后,在get缓存对象的时候,会统计命中情况:

/**
     * throw exception when value is null
     *
     * @param key
     * @return V
     * @throws UnCheckNullException
     * @throws LoadingFailException
     */
    public V get(Object key) throws LoadingFailException {
        CacheObject<K, V> object = delegate.get(key);

        if (object != null) {
            if(stats!=null){
                stats.hit();
            }

            object.setLastAccessTime(System.currentTimeMillis());
            return object.getValue();
        } else if(loader != null){
            V v;
            try {
                v = loader.load((K) key);
            } catch (Exception e) {
                throw new LoadingFailException("unable to load cache object");
            }

            if(stats != null){
                if(v == null){
                    stats.miss();
                } else {
                    stats.reload();
                }
            }

            super.put((K) key, v);
            object = delegate.get(key);
            object.setLastAccessTime(System.currentTimeMillis());
            return object.getValue();
        }

        throw new UnCheckNullException("cache object value can not is null");
    }

查询缓存命中情况时可以调用Cache.stat()方法:

 
public String stats(){
        return stats.toString();
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值