1. 程式人生 > >java實現本地快取

java實現本地快取

這裡本地快取的含義是 多個執行緒公用的一個靜態的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);
		}