GlobalCache 工具类

package com.neo.config;

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();

}
}


posted @ 2023-07-24 18:45  CGoodHabits  阅读(18)  评论(0)    收藏  举报