方法名称 | 方法说明 |
---|---|
put(String key , V value) | 向缓存中插入数据,数据永久有效 |
put(String key , V value , int seconds) | 向缓存中插入数据,数据根据设定的时间生效,时间到期会从缓存中移出 |
containKey(String key) | 判断缓存中是否包含对应的key |
get(String key) | 根据key从缓存中获取数据 |
remove(String key) | 移出缓存中对应key的数据 |
shutdownNow() | 关闭缓存池 |
本地缓存的设计如下图所示:
public interface LocalCache<V> { /** * 插入数据,数据永久有效 */ boolean put(String key, V value); /** * 插入数据,在指定时间内生效 */ boolean put(String key, V value, int seconds); /** * 是否包含指定的key */ boolean containKey(String key); /** * 获取指定Key的值 */ V get(String key); /** * 从缓存中移除key对应的数据 */ void remove(String key); void shutdownNow(); }在接口LocalCache中定义了两个数据插入的put接口:一个没有到期时间,另一个有到期时间。没有到期时间表示数据永久有效,有到期时间的数据会在到期后从缓存中移除。
public class DefaultLocalCache<V> implements LocalCache<V> { // 默认容量 private static final int DEFAULT_CAPACITY = 1024; private static final int MAX_CAPACITY = 100000; private static final int DEFAULT_THREAD_SIZE = 1; private final int maxSize; //数据map private volatile ConcurrentHashMap<String,V> dataMap; //过期时间 private final ConcurrentHashMap<String,Long> timeOutMap; // 堆代码 duidaima.com //定时任务 private final ScheduledExecutorService executorService; public DefaultLocalCache() { maxSize = MAX_CAPACITY; dataMap = new ConcurrentHashMap<>(DEFAULT_CAPACITY); timeOutMap = new ConcurrentHashMap<>(DEFAULT_CAPACITY); executorService = new ScheduledThreadPoolExecutor(DEFAULT_THREAD_SIZE) ; } public DefaultLocalCache(int size) { maxSize = size; dataMap = new ConcurrentHashMap<>(DEFAULT_CAPACITY); timeOutMap = new ConcurrentHashMap<>(DEFAULT_CAPACITY); executorService = new ScheduledThreadPoolExecutor(DEFAULT_THREAD_SIZE) ; } @Override public boolean put(String key, V value) { //检查容量 if(checkCapacity()){ dataMap.put(key,value); return true; } return false; } @Override public boolean put(String key, V value, int seconds) { if(checkCapacity()){ dataMap.put(key,value); if(seconds >= 0){ timeOutMap.put(key,getTimeOut(seconds)); ClearTask task = new ClearTask(key); executorService.schedule(task, seconds, TimeUnit.SECONDS); } } return false; } ...... class ClearTask implements Runnable{ private String key; public ClearTask(String key){ this.key = key; } @Override public void run() { //判断缓存中是否有key if(timeOutMap.contains(key)){ //获取失效时间 Long expire = timeOutMap.get(key); //如果失效时间大于0,并且比当前时间小,则删除缓存 if(expire > 0){ long now = System.currentTimeMillis(); if(now >= expire){ remove(key); } } } } } }在LocalCache的默认实现DefaultLocalCache中,基于ConcurrentHashMap与ScheduledThreadPoolExecutor结合使用,使得LocalCache支持永久缓存与临时缓存两种能力。