如果你想根据不同的缓存值(Value)设置不同的过期时间,可以考虑使用自定义缓存策略。下面是一个简单的示例:
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class CustomCache<K, V> {
private final Map<K, V> cache = new HashMap<>();
private final Map<K, Long> expirationTimes = new HashMap<>();
private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
public void put(K key, V value, long expirationTimeMillis) {
cache.put(key, value);
long expirationTime = System.currentTimeMillis() + expirationTimeMillis;
expirationTimes.put(key, expirationTime);
executorService.schedule(() -> {
if (System.currentTimeMillis() >= expirationTimes.getOrDefault(key, 0L)) {
remove(key);
}
}, expirationTimeMillis, TimeUnit.MILLISECONDS);
}
public V get(K key) {
return cache.getOrDefault(key, null);
}
public void remove(K key) {
cache.remove(key);
expirationTimes.remove(key);
}
public static void main(String[] args) {
CustomCache<String, Integer> cache = new CustomCache<>();
// 添加缓存项并设置不同的过期时间
cache.put("key1", 10, 5000); // 设置过期时间为5秒
cache.put("key2", 20, 10000); // 设置过期时间为10秒
try {
Thread.sleep(6000); // 等待6秒钟,模拟超时
System.out.println(cache.get("key1")); // 输出 null,已过期
System.out.println(cache.get("key2")); // 输出 20,尚未过期
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在上述示例中,我们使用cache
和expirationTimes
两个Map来分别存储缓存项和过期时间。当调用put
方法添加缓存项时,会同时设置对应的过期时间,并利用定时任务在指定的过期时间后自动删除缓存项。在获取缓存值时,会判断其是否已经过期。
请注意,这只是一个简单的示例实现,并不具备高并发和线程安全性,请根据实际需求进行适当优化和改进。
希望以上内容对你有所帮助!
内容由零声教学AI助手提供,问题来源于学员提问