缓存的几种方法
FIFO+过期时间
基于LinkedHashMap进行存储。
静态字段,一个存放数据的map,一个定时线程池。
// 存放缓存的集合
private Map<String, CacheData> cacheDatas = null;
// 定时器线程池,用于清楚过期缓存
private final static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5);
// FIFO
private static int MAX_CACHE_SIZE = 0;
private final float LOAD_FACTORY = 0.75f;
构造函数,设置缓存的大小。
public FIFOCacheProvider(int maxCacheSize){
MAX_CACHE_SIZE = maxCacheSize;
int capacity = (int)(Math.ceil(MAX_CACHE_SIZE/LOAD_FACTOR)+1);
cacheData = new LinkedHashMap<String, CacheData>(capacity, LOAD_FACTOR, false){
@Override
protected boolean removeEldestEntry(Map.Entry<String, CacheData> eldest){
return size() > MAX_CACHE_SIZE;
}
};
}
get,读取缓存
public synchronized <T> T get(String key) {
CacheData cacheData = cacheDatas.get(key);
return cacheData == null ? null : (T) cacheData.data;
}
put方法,不用的失效时间的方法
public synchronized void put(String key, Object v){
this.put(key, value, -1L);
}
put方法,使用失效时间的方法
public synchronized void put(String key, Object v, Long expire){
// 如果没有啥也不做,如果有的话,就清除。
cacheData.remove(key);
if(expire > 0){
executor.schedule(new Runnable(){
@Override
public void run(){
synchronized(this){
cacheDatas.remove(key);
}
}
}, expire, TimeUnit.MILLISECONDS);
cacheData.put(key, new CacheData(value, expire));
} else {
cacheData.put(key, new CacheData(value, -1L));
}
}
remove
public synchronized <T> T remove(String key){
CacheData cacheData = cacheData.remove(key);
return cacheData == null ? null : (T) cacheData.data;
}
就普通的缓存+过期时间
基于ConcurrentHashMap进行存储。
静态字段,一个存放数据的map,一个定时线程池。
private final static Map<String, CacheData> cacheDatas = new ConcurrentHashmap<>();
private final static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5);
get方法
public synchronized <T> T get(String key){
CacheData cacheData = cacheDatas.get(key);
return cacheData == null? null:(T)cacheData.data;
}
put方法,不用的失效时间的方法
public synchronized void put(String key, Object v){
this.put(key, value, -1L);
}
put方法,使用失效时间的方法
public synchronized void put(String key, Object v, Long expire){
// 如果没有啥也不做,如果有的话,就清除。
cacheData.remove(key);
if(expire > 0){
executor.schedule(new Runnable(){
@Override
public void run(){
synchronized(this){
cacheDatas.remove(key);
}
}
}, expire, TimeUnit.MILLISECONDS);
cacheData.put(key, new CacheData(value, expire));
} else {
cacheData.put(key, new CacheData(value, -1L));
}
}
remove
public synchronized <T> T remove(String key){
CacheData cacheData = cacheData.remove(key);
return cacheData == null ? null : (T) cacheData.data;
}
size()就return cacheData.size();
所有操作都要加synchronized锁