java實現本機快取

來源:互聯網
上載者:User
這裡本機快取的含義是 多個線程公用的一個靜態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);}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.