這裡本機快取的含義是 多個線程公用的一個靜態Map對象
作用是減少db或cache的查詢次數。
使用情境為靜態或者非敏感性資料。
也可以使用google的guava cache等
緩衝類
import lombok.AllArgsConstructor;import lombok.Getter;import lombok.Setter;import java.util.HashMap;import java.util.Map;public class LocalCache { //緩衝Map private static Map<String,CacheContent> map = new HashMap<>(); private static LocalCache localCache = new LocalCache(); private LocalCache(){ } public String getLocalCache(String key) { CacheContent cc = map.get(key); if(null == cc) { return null; } long currentTime = System.currentTimeMillis(); if(cc.getCacheMillis() > 0 && currentTime - cc.getCreateTime() > cc.getCacheMillis()) { //超過緩衝到期時間,返回null map.remove(key); return null; } else { return cc.getElement(); } } public void setLocalCache(String key,int cacheMillis,String value) { long currentTime = System.currentTimeMillis(); CacheContent cc = new CacheContent(cacheMillis,value,currentTime); map.put(key,cc); } public static LocalCache getInStance(){ return localCache; } @Getter @Setter @AllArgsConstructor class CacheContent{ // 緩衝生效時間 private int cacheMillis; // 緩衝對象 private String element; // 緩衝建立時間 private long createTime ; }}
調用代碼
//先查詢本機快取 String key ="testkey";LocalCache localCache = LocalCache.getInStance();String value = localCache.getLocalCache(key);if(StringUtils.isBlank(value)) { //從db或cache擷取資料value = RedisClient.get(key);//設定本機快取,生效時間為10秒localCache.setLocalCache(key ,10000,value);}