以下是一个简单的时间轮本地缓存的 Java 实现示例代码:

import java.util.*;
import java.util.concurrent.*;

class CacheItem<T> {
    private T data;
    private long expirationTime;

    public CacheItem(T data, long expirationTime) {
        this.data = data;
        this.expirationTime = expirationTime;
    }

    public T getData() {
        return data;
    }

    public long getExpirationTime() {
        return expirationTime;
    }
}

public class LocalCache<T> {
    private final Map<String, CacheItem<T>> cacheMap;
    private final ScheduledExecutorService scheduler;

    public LocalCache() {
        cacheMap = new ConcurrentHashMap<>();
        scheduler = Executors.newSingleThreadScheduledExecutor();
    }

    public void put(String key, T data, long expirationTime) {
        CacheItem<T> cacheItem = new CacheItem<>(data, expirationTime);
        cacheMap.put(key, cacheItem);
        scheduleExpiration(key, expirationTime);
    }

    public T get(String key) {
        CacheItem<T> cacheItem = cacheMap.get(key);
        if (cacheItem != null && cacheItem.getExpirationTime() > System.currentTimeMillis()) {
            return cacheItem.getData();
        }
        return null;
    }

    public void remove(String key) {
        cacheMap.remove(key);
    }

    private void scheduleExpiration(String key, long expirationTime) {
        scheduler.schedule(() -> {
            cacheMap.remove(key);
        }, expirationTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    public void shutdown() {
        scheduler.shutdown();
    }
}

// 示例用法
public class Main {
    public static void main(String[] args) {
        LocalCache<String> cache = new LocalCache<>();
        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

        try {
            Thread.sleep(6000); // 等待6秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(cache.get('key1')); // 输出: null,已过期
        System.out.println(cache.get('key2')); // 输出: value2

        cache.shutdown();
    }
}

在这个示例中,LocalCache类是一个本地缓存实现,使用ConcurrentHashMap作为缓存的容器。每个缓存条目都包含数据和过期时间。当调用put方法放入新的缓存条目时,会创建一个新的CacheItem对象,并将其添加到cacheMap中,并且调用scheduleExpiration方法来安排过期清理任务。

scheduleExpiration方法使用ScheduledExecutorService来调度一个任务,在指定的过期时间后执行清理操作,即从cacheMap中移除对应的缓存条目。

get方法用于获取缓存中指定键的值。如果缓存条目存在且未过期,则返回对应的数据,否则返回null。

remove方法用于从缓存中移除指定键的缓存条目。

在示例的主函数中,演示了如何使用LocalCache类来进行缓存的放入和获取操作,并且通过等待一段时间来触发缓存的过期。最后,需要调用shutdown方法来停止ScheduledExecutorService的运行。

Java 时间轮本地缓存实现:自动清理过期数据示例

原文地址: https://www.cveoy.top/t/topic/qDt3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录