单列模式下(缓存)


import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MapCache {
private static volatile MapCache mapCache;
/**
* 默认缓存容量
*/
private static final int INITIAL_CAPACITY = 1024;

/**
* 缓存容器
*/
private final Map<String, Object> cachePool;

/**
* 定时器 用来控制 缓存的超时时间
*/
private final ScheduledExecutorService executorService;

private MapCache(int initialCapacity) {

cachePool = new ConcurrentHashMap<>(initialCapacity);
executorService = new ScheduledThreadPoolExecutor(2);
}


public static MapCache getInstance(){
if (mapCache == null){
synchronized (MapCache.class) {
if (mapCache == null) {
mapCache = new MapCache();
}
}
}
return mapCache;
}

public MapCache() {
this(INITIAL_CAPACITY);
}

/**
* 设置缓存 无过期时间
*
* @param key 键
* @param value 值
*/
public void put(String key, Object value) {
cachePool.put(key, value);
}

/**
* 设置缓存 有过期时间
*
* @param key 键
* @param value 值
* @param timeout 过期时间
*/
public void put(String key, Object value, int timeout) {
cachePool.put(key, value);
executorService.schedule(() -> remove(key), timeout, TimeUnit.SECONDS);
}

/**
* 读取缓存
*
* @param key 键
* @return 返回值
*/
public Object get(String key) {
return cachePool.get(key);
}

/**
* 获取所有key
*
* @return 获取所有key
*/
public Set<String> getKeys() {
return cachePool.keySet();
}

/**
* 获取当前缓存所有内容
* @return
*/
public Map<String ,Object> allCache(){
return cachePool;
}

/**
* 判断缓存是否包含key
* @param key key
* @return 是否包含
*/
public boolean containsKey(String key){
return cachePool.containsKey(key);
}


/**
* 获取当前缓存大小
*
* @return 缓存大小
*/
public int size() {
return cachePool.size();
}

/**
* 根据key删除缓存
*
* @param key key
*/
public void remove(String key) {
cachePool.remove(key);
}

/**
* 清空缓存
*/
public void clean() {
if (size() > 0) {
cachePool.clear();
}
}

}
业务要求较高推荐 ConcurrentHashMap  

posted @ 2023-03-30 11:24  以后啊  阅读(10)  评论(0编辑  收藏  举报