Cache2j:进阶之Stats讲解

版权声明:请勿作为商业用途!未经博主允许请勿转载!谢谢支持! https://blog.csdn.net/u012737673/article/details/79295851

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();
}

猜你喜欢

转载自blog.csdn.net/u012737673/article/details/79295851
今日推荐