java实现带过期时间的缓存

直接上代码
package com.dyh.utils;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.PriorityQueue;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

public class LocalCache {
    private static ScheduledExecutorService swapExpiredPool
            = new ScheduledThreadPoolExecutor(10);

    private ReentrantLock lock = new ReentrantLock();

    private ConcurrentHashMap<String, Node> cache = new ConcurrentHashMap<>(1024);
    /**
     * 让过期时间最小的数据排在队列前,在清除过期数据时
     * ,只需查看缓存最近的过期数据,而不用扫描全部缓存
     *
     * @see Node#compareTo(Node)
     * @see SwapExpiredNodeWork#run()
     */
    private PriorityQueue<Node> expireQueue = new PriorityQueue<>(1024);

    public LocalCache() {

        //使用默认的线程池,每5秒清除一次过期数据
        //线程池和调用频率 最好是交给调用者去设置。
        swapExpiredPool.scheduleWithFixedDelay(
               
  • 1
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
你可以使用 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 秒遍历缓存并删除过期数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值