package com.neo.config;标签:GlobalCache,cacheMap,cache,key,import,工具,public From: https://www.cnblogs.com/mssrecord/p/17578058.html
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Component
public class GlobalCache {
private Map<String, Object> cacheMap;
private ScheduledExecutorService executorService;
public GlobalCache() {
this.cacheMap = new ConcurrentHashMap<>();
this.executorService = Executors.newSingleThreadScheduledExecutor();
}
public void put(String key, Object value, long expiringTime, TimeUnit timeUnit) {
this.cacheMap.put(key, value);
this.executorService.schedule(() -> this.cacheMap.remove(key), expiringTime, timeUnit);
}
public Object get(String key) {
return this.cacheMap.get(key);
}
public void remove(String key) {
this.cacheMap.remove(key);
}
public void clear() {
this.cacheMap.clear();
}
public void stop() {
this.executorService.shutdown();
}
public static void main(String[] args) throws InterruptedException {
GlobalCache cache = new GlobalCache();
cache.put("key1", "value1", 2, TimeUnit.SECONDS);
System.out.println(cache.get("key1")); // value1
Thread.sleep(3000);
System.out.println(cache.get("key1")); // null
cache.stop();
}
}