读代码Guava的CacheLoader

Posted 盖丽男

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读代码Guava的CacheLoader相关的知识,希望对你有一定的参考价值。

来看一段代码,代码中有两个打日志的地方,请问哪个会先打印出来?
这里使用的是Guava的CacheLoader

package com.example.demo.config;

import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class CancelTypeCacheMap implements CommandLineRunner 
    // 默认值
    private static HashMap<String, String> DEFAULT_CACHE_MAP = new HashMap<String, String>() 
        
            put("0", "取消1");
            put("1", "取消2");
            put("3", "取消3");
            put("4", "取消4");
        
    ;

    private static volatile LoadingCache<String, HashMap<String, String>> cache;
    private static final String CANCEL_TYPE_DESC_LIST_KEY = "cancelTypeDescList";


    @Override
    public void run(String... args) throws Exception 
        if (cache == null) 
            cache = CacheBuilder.newBuilder()
                    .refreshAfterWrite(30, TimeUnit.MINUTES).build(new CacheLoader<String, HashMap<String, String>>() 
                        @Override
                        public HashMap<String, String> load(String key) throws Exception 
                            //第一个log
                            log.info("cancelTypeDesc加载完成:",DEFAULT_CACHE_MAP);
                            return DEFAULT_CACHE_MAP;
                        
                    );
             //第二个log
            log.info("cancelTypeDescLoadingCache is ",cache);
            cache.get(CANCEL_TYPE_DESC_LIST_KEY);
        
    





当然是第二个先打印,可是我当时没理解为啥是这样,看了看代码有了以下理解:

上面那段,run方法的代码可以写成下面这样:

    @Override
    public void run(String... args) throws Exception 


        if (cache == null) 
            CacheLoader<String, HashMap<String, String>> load= new CacheLoader<String, HashMap<String, String>>() 
                @Override
                public HashMap<String, String> load(String key) throws Exception 
                    log.info("map加载完成:",DEFAULT_CACHE_MAP);
                    return DEFAULT_CACHE_MAP;
                
            ;


            cache = CacheBuilder.newBuilder()
                    .refreshAfterWrite(30, TimeUnit.MINUTES).build(load);
            log.info("cancelTypeDescLoadingCache is ", cache);
            HashMap<String, String> result= cache.get(CANCEL_TYPE_DESC_LIST_KEY);
            log.info("result is ", JSONObject.toJSONString(result));
        
    

然后还需要注意的一点在于,cache.get方法,点进去可以看到:

    @Override
    public V get(K key) throws ExecutionException 
      return localCache.getOrLoad(key);
    

也就是说,当已经有数据的时候,会get,当没有数据的时候,就会load,而我们初始化CacheLoader的时候,实现了load方法,那么为什么是这么写的呢?

因为CacheLoader是一个抽象类,load是一个抽象方法,当我们实例化,也就是new它的时候,必须先实现load方法。

public abstract class CacheLoader<K, V> 

  /**
   * Computes or retrieves the value corresponding to @code key.
   *
   * @param key the non-null key whose value should be loaded
   * @return the value associated with @code key; <b>must not be null</b>
   * @throws Exception if unable to load the result
   * @throws InterruptedException if this method is interrupted. @code InterruptedException is
   *     treated like any other @code Exception in all respects except that, when it is caught,
   *     the thread's interrupt status is set
   */
  public abstract V load(K key) throws Exception;

以上是关于读代码Guava的CacheLoader的主要内容,如果未能解决你的问题,请参考以下文章

Guava Cache

Google guava cache源码解析1--构建缓存器

Google guava cache源码解析1--构建缓存器

如何使用Guava的缓存管理

guava怎么读

一文读懂Guava EventBus(订阅发布事件)