带有过期时效的Map

https://blog.csdn.net/weixin_43627880/article/details/105855942

https://blog.csdn.net/qq_33407429/article/details/96592358

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Java 中的 ConcurrentHashMap 数据结构和 ScheduledExecutorService 实现过期时间的缓存。具体实现步骤如下: 1. 创建一个 ConcurrentHashMap 对象来存储缓存数据,key 为缓存的键,value 为缓存的值和过期时间。 2. 创建一个 ScheduledExecutorService 组件,用来定期清理过期缓存。 3. 实现一个 put 方法来向缓存中添加数据,该方法会将数据存入 ConcurrentHashMap 中,并且将过期时间也存入 value 中。 4. 实现一个 get 方法来从缓存中获取数据,该方法会先检查数据是否过期,如果过期则删除该数据并返回 null,否则返回缓存数据的值。 5. 实现一个定时任务,定期遍历 ConcurrentHashMap,删除过期的缓存数据。 实现代码示例: ```java import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ExpireCache<K, V> { private final ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<>(); private final ConcurrentHashMap<K, Long> expireTime = new ConcurrentHashMap<>(); private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); public ExpireCache() { // 定时任务,每隔 1 秒遍历缓存并删除过期数据 executorService.scheduleWithFixedDelay(() -> { long now = System.currentTimeMillis(); cache.forEach((k, v) -> { Long expire = expireTime.get(k); if (expire != null && now > expire) { cache.remove(k); expireTime.remove(k); } }); }, 1, 1, TimeUnit.SECONDS); } public void put(K key, V value, long expireAfter) { cache.put(key, value); expireTime.put(key, System.currentTimeMillis() + expireAfter); } public V get(K key) { V value = cache.get(key); if (value != null) { Long expire = expireTime.get(key); if (expire == null || System.currentTimeMillis() <= expire) { return value; } else { cache.remove(key); expireTime.remove(key); } } return null; } } ``` 使用示例: ```java ExpireCache<String, String> cache = new ExpireCache<>(); cache.put("key1", "value1", 5000); // 缓存 5 秒 cache.put("key2", "value2", 10000); // 缓存 10 秒 // 获取缓存数据 System.out.println(cache.get("key1")); // 输出 value1 System.out.println(cache.get("key2")); // 输出 value2 Thread.sleep(6000); // 等待 6 秒 // 获取缓存数据 System.out.println(cache.get("key1")); // 输出 null System.out.println(cache.get("key2")); // 输出 value2 Thread.sleep(5000); // 等待 5 秒 // 获取缓存数据 System.out.println(cache.get("key2")); // 输出 null ``` 在上述示例中,使用 ExpireCache 类来实现过期时间的缓存,缓存数据的过期时间分别为 5 秒和 10 秒。在获取缓存数据时,如果数据已经过期,则返回 null,否则返回缓存数据的值。缓存数据的清理是通过定时任务来实现的,每隔 1 秒遍历缓存并删除过期数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值