天天看點

Cache的使用

1.Google Guava Cache

@Slf4j
public class CaCheUtil {

    private CaCheUtil() {
    }
    
    public static class StaticCache {

        private static final Cache<String, Object> cache =
            CacheBuilder.newBuilder().
                expireAfterWrite(5, TimeUnit.MINUTES).build();
    }

    public static Object getCache(String key) {

        try {
            return
                StaticCache.cache.get(key, () -> {
                    return getDBBy(key);
                });
        } catch (ExecutionException e) {
            log.info("get cache is fail", e);
        }
        return null;
    }

    /**
     * 這裡實作查詢資料庫的操作
     */
    public static Object getDBBy(String key) {
        log.info("-----------------查DB");
        return "getDB";
    }

    public Object getLoadCaChe(String key) {
        LoadingCache<String, Object> loadCache = CacheBuilder.newBuilder().
            expireAfterWrite(5, TimeUnit.MINUTES).
            build(new CacheLoader<String, Object>() {
                @Override
                public Object load(String key) throws Exception {
                    return getDBBy(key);
                }
            });
        try {
            return loadCache.get(key);
        } catch (ExecutionException e) {
            log.info("get cache is fail", e);
        }
        return null;
    }


}
           

參數介紹:

expireAfterWrite是在指定項在一定時間内沒有建立/覆寫時,會移除該key,下次取的時候從loading中取

expireAfterAccess是指定項在一定時間内沒有讀寫,會移除該key,下次取的時候從loading中取

refreshAfterWrite是在指定時間内沒有被建立/覆寫,則指定時間過後,再次通路時,會去重新整理該緩存,在新值沒有到來之前,始終傳回舊值

跟expire的差別是,指定時間過後,expire是remove該key, 下次通路是同步去擷取傳回新值;而refresh則是指定時間後,不會remove該key,

下次通路會觸發重新整理,新值沒有回來時傳回舊值

Maven依賴

<dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>20.0</version>
    </dependency>
           

其他請通路官網:https://github.com/google/guava/wiki/CachesExplained

http://ifeve.com/google-guava-cachesexplained/

Caffeine https://www.jianshu.com/p/ba2ac225836d

https://wujiazhen2.github.io/2018/09/30/Caffeine/