面試官:你是如何使用JDK來實現自己的緩存(支持高併發)?

需求分析

項目中經常會遇到這種場景:一份數據需要在多處共享,有些數據還有時效性,過期自動失效。比如手機驗證碼,發送之後需要緩存起來,然後處於安全性考慮,一般還要設置有效期,到期自動失效。我們怎麼實現這樣的功能呢?

解決方案

使用現有的緩存技術框架,比如redis,ehcache。優點:成熟,穩定,功能強大;缺點,項目需要引入對應的框架,不夠輕量。

如果不考慮分佈式,只是在單線程或者多線程間作數據緩存,其實完全可以自己手寫一個緩存工具。下面就來簡單實現一個這樣的工具。

先上代碼:

import java.util.HashMap; import java.util.Map; import java.util.concurrent.*; /** * @Author: lixk
 * @Date: 2018/5/9 15:03
 * @Description: 簡單的內存緩存工具類 */
public class Cache { //鍵值對集合
    private final static Map<String, Entity> map = new HashMap<>(); //定時器線程池,用於清除過期緩存
    private final static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); /** * 添加緩存
     *
     * @param key  鍵
     * @param data 值 */
    public synchronized static void put(String key, Object data) {
        Cache.put(key, data, 0);
    } /** * 添加緩存
     *
     * @param key    鍵
     * @param data   值
     * @param expire 過期時間,單位:毫秒, 0表示無限長 */
    public synchronized static void put(String key, Object data, long expire) { //清除原鍵值對
 Cache.remove(key); //設置過期時間
        if (expire > 0) {
            Future future = executor.schedule(new Runnable() {
                @Override public void run() { //過期後清除該鍵值對
                    synchronized (Cache.class) {
                        map.remove(key);
                    }
                }
            }, expire, TimeUnit.MILLISECONDS);
            map.put(key, new Entity(data, future));
        } else { //不設置過期時間
            map.put(key, new Entity(data, null));
        }
    } /** * 讀取緩存
     *
     * @param key 鍵
     * @return
     */
    public synchronized static Object get(String key) {
        Entity entity = map.get(key); return entity == null ? null : entity.getValue();
    } /** * 讀取緩存
     *
     * @param key 鍵
     *            * @param clazz 值類型
     * @return
     */
    public synchronized static <T> T get(String key, Class<T> clazz) { return clazz.cast(Cache.get(key));
    } /** * 清除緩存
     *
     * @param key
     * @return
     */
    public synchronized static Object remove(String key) { //清除原緩存數據
        Entity entity = map.remove(key); if (entity == null) return null; //清除原鍵值對定時器
        Future future = entity.getFuture(); if (future != null) future.cancel(true); return entity.getValue();
    } /** * 查詢當前緩存的鍵值對數量
     *
     * @return
     */
    public synchronized static int size() { return map.size();
    } /** * 緩存實體類 */
    private static class Entity { //鍵值對的value
        private Object value; //定時器Future 
        private Future future; public Entity(Object value, Future future) { this.value = value; this.future = future;
        } /** * 獲取值
         *
         * @return
         */
        public Object getValue() { return value;
        } /** * 獲取Future對象
         *
         * @return
         */
        public Future getFuture() { return future;
        }
    }
}

本工具類主要採用 HashMap+定時器線程池 實現,map 用於存儲鍵值對數據,map的value是 Cache 的內部類對象 Entity,Entity 包含 value 和該鍵值對的生命週期定時器 Future。Cache 類對外只提供了 put(key, value), put(key, value, expire), get(key), get(key, class), remove(key), size()幾個同步方法。

當添加鍵值對數據的時候,首先會調用remove()方法,清除掉原來相同 key 的數據,並取消對應的定時清除任務,然後添加新數據到 map 中,並且,如果設置了有效時間,則添加對應的定時清除任務到定時器線程池。

在這裏給大家風向一波免費Java資源包括分佈式,微服務,併發,面試,Java架構師成長路線等等資源
加QQ:2995457287 或 vx:gupao-cola 免費獲取。

測試

import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * @Author: lixk
 * @Date: 2018/5/9 16:40
 * @Description: 緩存工具類測試 */
public class CacheTest { /** * 測試
     *
     * @param args */
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        String key = "id"; //不設置過期時間
        System.out.println("***********不設置過期時間**********");
        Cache.put(key, 123);
        System.out.println("key:" + key + ", value:" + Cache.get(key));
        System.out.println("key:" + key + ", value:" + Cache.remove(key));
        System.out.println("key:" + key + ", value:" + Cache.get(key)); //設置過期時間
        System.out.println("\n***********設置過期時間**********");
        Cache.put(key, "123456", 1000);
        System.out.println("key:" + key + ", value:" + Cache.get(key));
        Thread.sleep(2000);
        System.out.println("key:" + key + ", value:" + Cache.get(key)); /******************併發性能測試************/ System.out.println("\n***********併發性能測試************"); //創建有10個線程的線程池,將1000000次操作分10次添加到線程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Future[] futures = new Future[10]; /********添加********/ { long start = System.currentTimeMillis(); for (int j = 0; j < 10; j++) {
                futures[j] = executorService.submit(() -> { for (int i = 0; i < 100000; i++) {
                        Cache.put(Thread.currentThread().getId() + key + i, i, 300000);
                    }
                });
            } //等待全部線程執行完成,打印執行時間
            for (Future future : futures) {
                future.get();
            }
            System.out.printf("添加耗時:%dms\n", System.currentTimeMillis() - start);
        } /********查詢********/ { long start = System.currentTimeMillis(); for (int j = 0; j < 10; j++) {
                futures[j] = executorService.submit(() -> { for (int i = 0; i < 100000; i++) {
                        Cache.get(Thread.currentThread().getId() + key + i);
                    }
                });
            } //等待全部線程執行完成,打印執行時間
            for (Future future : futures) {
                future.get();
            }
            System.out.printf("查詢耗時:%dms\n", System.currentTimeMillis() - start);
        }

        System.out.println("當前緩存容量:" + Cache.size());
    }
}

測試結果:

***********不設置過期時間********** key:id, value:123 key:id, value:123 key:id, value:null

***********設置過期時間********** key:id, value:123456 key:id, value:null

***********併發性能測試************ 添加耗時:2313ms
查詢耗時:335ms
當前緩存容量:1000000

測試程序使用有10個線程的線程池來模擬併發,總共執行一百萬次添加和查詢操作,時間大約都在兩秒多,`表現還不錯,每秒40萬讀寫併發應該還是可以滿足大多數高併發場景的_

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章