[Google Guava]学习--缓存cache

适用性

  缓存在不少状况下很是实用。例如,计算或检索一个值的代价很高,而且对一样的输入须要不止一次获取值的时候,就应当考虑使用缓存。html

  Guava CacheConcurrentMap很类似,但也不彻底同样。最基本的区别是ConcurrentMap会一直保存所添加的元素,直到显式的移除Guava Cache为了限制内存的占用,一般都是设定为自动回收元素。在某些场景下,尽管LoadingCahe不回收元素,可是它仍是颇有用的,由于它会自动加载缓存。java

  Guava Cache适用场景:git

  • 你愿意消耗一部份内存来提高速度;
  • 你已经预料某些值会被屡次调用;
  • 缓存数据不会超过内存总量;

 Guava Cache是一个全内存的本地缓存实现,它提供了线程安全的实现机制。总体上来讲Guava cache 是本地缓存的不二之选,简单易用,性能好。redis

建立方式

  CacheLoaderCallable经过这两种方法建立的cache,和一般用map来缓存的作法比,不一样在于这两种方法都实现了一种逻辑——从缓存中取key X的值,若是该值已经缓存过了,则返回缓存中的值,若是没有缓存过,能够经过某个方法来获取这个值。数据库

  但不一样的在于cacheloader的定义比较宽泛, 是针对整个cache定义的,能够认为是统一的根据key值load value的方法。而callable的方式较为灵活,容许你在get的时候指定。api

  一、CacheLoader缓存

public class AppkeyInfoLocalCache {

    private static Logger log = Logger.getLogger(AppkeyInfoLocalCache.class);

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

                /** 数据库进行查询 **/
                private AppkeyInfoBasic getAppkeyInfo(String appKey) throws DaoException {
                    log.info("method<getAppkeyInfo> get AppkeyInfo form DB appkey<" + appKey + ">");
                    return ((AppkeyInfoMapper) SpringContextHolder.getBean("appkeyInfoMapper"))
                            .selectAppkeyInfoByAppKey(appKey);
                }
            });

    public static AppkeyInfoBasic getAppkeyInfoByAppkey(String appKey) throws DaoException, ExecutionException {
        log.info("method<getAppkeyInfoByAppkey> appkey<" + appKey + ">");
        return cache.get(appKey);
    }

}

  二、Callable安全

   public void testcallableCache()throws Exception{
        Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).build();  
        String resultVal = cache.get("jerry", new Callable<String>() {  
            public String call() {  
                String strProValue="hello "+"jerry"+"!";                
                return strProValue;
            }  
        });  
        System.out.println("jerry value : " + resultVal);
        
        resultVal = cache.get("peida", new Callable<String>() {  
            public String call() {  
                String strProValue="hello "+"peida"+"!";                
                return strProValue;
            }  
        });  
        System.out.println("peida value : " + resultVal);  
    }
相关文章
相关标签/搜索