package com.community.huiju.common.code.cache;

import com.community.commom.constant.Constant;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 缓存
 * @author weiximei
 */
@Slf4j
public class AppkeyCache {

    // 给定时间内没有被读/写访问，则回收。
    // .refreshAfterWrite(3, TimeUnit.HOURS)
    static LoadingCache<String, Object> cache = CacheBuilder.newBuilder()
            // 缓存过期时间和redis缓存时长一样
            .expireAfterAccess(Constant.CACHE_EXPIRE, TimeUnit.HOURS)
            // 设置缓存个数
            .maximumSize(Constant.CACHE_SIZE).
            build(new CacheLoader<String, Object>() {
            @Override
            /** 当本地缓存命没有中时，调用load方法获取结果并将结果缓存 **/
            public String load(String appKey) throws Exception {
                return null;
            }

    });

    public static Object getCache(String appKey) {
        Object value = null;
        try {
            value = cache.get(appKey);
        } catch (Exception e) {
            //e.printStackTrace();
            value = null;
        }
        return value;
    }

    public static void setCache(String appKey,Object appValue){
        log.info("缓存的key-value: {}-{}", appKey,appValue);
        cache.put(appKey,appValue);
    }


}
