【读代码】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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盖丽男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值