手写一个全局的map缓存,要求每隔指定时间自动过期

  • 作者: 凯哥Java(公众号:凯哥Java)
  • 工作小总结
  • 时间:2023-05-10 18:47
  • 1798人已阅读
简介 思路:可以使用Java中的ConcurrentHashMap和ScheduledExecutorService实现一个全局的map缓存,这里提供一个简单的实现:import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.Executors;

🔔🔔好消息!好消息!🔔🔔

 如果您需要注册ChatGPT,想要升级ChatGPT4。凯哥可以代注册ChatGPT账号代升级ChatGPT4

有需要的朋友👉:微信号 kaigejava2022

思路:

可以使用Java中的ConcurrentHashMap和ScheduledExecutorService实现一个全局的map缓存,这里提供一个简单的实现:

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

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 class Main {
    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();
    }
}

在这个示例中,我们使用ConcurrentHashMap作为底层实现,并使用ScheduledExecutorService来定时清理过期的缓存项。在put方法中,我们指定了缓存项的过期时间,然后在指定时间后使用ScheduledExecutorService来执行缓存项的清理操作。在get、remove和clear方法中,我们只是简单地包装了底层的ConcurrentHashMap的方法。

需要注意的是,在使用ScheduledExecutorService时,我们需要在程序结束时显式地调用stop方法来停止线程池的运行。



TopTop