Guava本地内存缓存

import cn.com.flaginfo.platform.umsapp.common.utils.RedisUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.CacheStats;
import com.google.common.cache.LoadingCache;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class LocalCacheEntity {

    public final String id;

    public final LoadingCache<Object, Object> cache;

    // 缓存启动时间
    final Date startTime;

    // 缓存出现峰值时间
    public Date highestTime = null;

    // 缓存峰值大小
    public long highestSize = 0;

    // 本地缓存最大个数,默认1000
    long maximumSize;

    // 本地缓存有效时间(秒),默认是10s
    long expireAfterWriteDuration;

    /**
     * @param id    缓存id
     * @param maximumSize   最大缓存数量,必须从配置文件读取
     * @param expireAfterWriteDuration  缓存过期时间必须从配置文件读取
     */
    public LocalCacheEntity(String id, long maximumSize, long expireAfterWriteDuration) {
        this.cache = CacheBuilder
                .newBuilder()
                .maximumSize(maximumSize)
                .expireAfterWrite(expireAfterWriteDuration,
                        TimeUnit.SECONDS).recordStats()
                .build(new CacheLoader<Object, Object>() {
                    public Object load(Object key) throws Exception {
                        return null;
                    }
                });

        this.id = id;
        this.startTime = new Date();
        this.maximumSize = maximumSize;
        this.expireAfterWriteDuration = expireAfterWriteDuration;

    }

    /**
     * 添加gava缓存
     *
     * @param key
     * @param value
     */
    public void putObject(Object key, Object value) {
        try {
            this.cache.put(key, value);
        } catch (Exception e) {
        }
    }

    /**
     * 获取gava缓存
     *
     * @param key
     * @return
     */
    public Object getObject(Object key) {
        Object answer = null;
        try {
            answer = this.cache.get(key);
            if (this.cache.size() > this.highestSize) {
                this.highestSize = this.cache.size();
                this.highestTime = new Date();
            }
        } catch (Exception e) {
        }
        return answer;
    }

    /**
     * 从本地缓存中获取值,如果本地缓存中不存在,则从redis中获取
     *
     * @param key
     * @return
     */
    public Object getObject(String key, RedisUtils redisUtils) {
        Object answer = null;
        try {
            answer = this.cache.get(key);
            if (this.cache.size() > this.highestSize) {
                this.highestSize = this.cache.size();
                this.highestTime = new Date();
            }
        } catch (Exception e) {
        }
        if( null == answer ){ //本地缓存不存在,则在redis中获取
            answer = redisUtils.get(key);
            if( null != answer ){ //redis中存在,则要把redis中值缓存到本地缓存中
                this.putObject(key, answer);
            }
        }
        return answer;
    }

    /**
     * 删除gava缓存
     *
     * @param key
     * @return
     */
    public Object removeObject(Object key) {
        Object answer = null;
        try {
            answer = getObject(key);
            this.cache.invalidate(key);
        } catch (Exception e) {

        }
        return answer;
    }

    /**
     * 清除所有缓存
     */
    public void clear() {
        try {
            this.cache.invalidateAll();
        } catch (Exception e) {
        }
    }

    /**
     * 缓存gava缓存大小
     *
     * @return
     */
    public int getSize() {
        int answer = 0;
        try {
            answer = (int) this.cache.size();
        } catch (Exception e) {
        }
        return answer;
    }

    public JSONObject getStats(){
        JSONObject json = new JSONObject();
        //Map<String, Object> map = new LinkedHashMap<>();
        CacheStats cs = this.cache.stats();
        NumberFormat percent = NumberFormat.getPercentInstance(); // 建立百分比格式化用
        percent.setMaximumFractionDigits(1); // 百分比小数点后的位数
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        json.put("缓存id", this.id);
        json.put("当前缓存大小", cache.size());
        json.put("缓存最大值", this.maximumSize);
        json.put("缓存过期时间", this.expireAfterWriteDuration);
        json.put("命中次数", cs.hitCount());
        json.put("缓存命中率", percent.format(cs.hitRate()));
        json.put("缓存失效率", percent.format(cs.missRate()));
        json.put("缓存启动时间", df.format(this.startTime));
        json.put("缓存最大峰值", this.highestSize);
        if (this.highestTime != null)
            json.put("缓存最大峰值时间", df.format(this.highestTime));

        return json;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值