[Google Guava]学习--缓存cache

适用性

  缓存在很多情况下非常实用。例如,计算或检索一个值的代价很高,并且对同样的输入需要不止一次获取值的时候,就应当考虑使用缓存。

  Guava CacheConcurrentMap很相似,但也不完全一样。最基本的区别是ConcurrentMap会一直保存所添加的元素,直到显式的移除Guava Cache为了限制内存的占用,通常都是设定为自动回收元素。在某些场景下,尽管LoadingCahe不回收元素,但是它还是很有用的,因为它会自动加载缓存。

  Guava Cache适用场景:

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

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

创建方式

  CacheLoaderCallable通过这两种方法创建的cache,和通常用map来缓存的做法比,不同在于这两种方法都实现了一种逻辑——从缓存中取key X的值,如果该值已经缓存过了,则返回缓存中的值,如果没有缓存过,可以通过某个方法来获取这个值。

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

  1、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);
    }

}

  2、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);  
    }
原文地址:https://www.cnblogs.com/parryyang/p/5777019.html