ConcurrentHashMapString Object 实现代替redis过期时间设置一样
ConcurrentHashMap<String, Object> 是 Java 提供的线程安全的哈希表实现,可以用来存储键值对数据。要实现与 Redis 过期时间设置一样的功能,可以通过以下步骤:
- 创建一个 ConcurrentHashMap 对象,用来存储键值对数据。
ConcurrentHashMap<String, Object> cache = new ConcurrentHashMap<>();
- 定义一个过期时间常量,表示数据的有效期,单位可以是秒或毫秒。
private static final long EXPIRE_TIME = 60000; // 60秒
- 在插入数据时,同时记录数据的插入时间。
cache.put(key, value);
long currentTime = System.currentTimeMillis();
- 在获取数据时,判断数据是否过期,如果过期则移除数据并返回 null,否则返回对应的值。
Object value = cache.get(key);
if (value != null) {
long insertTime = (long) cache.get(key + "_time");
if (currentTime - insertTime > EXPIRE_TIME) {
cache.remove(key);
cache.remove(key + "_time");
value = null;
}
}
return value;
- 可以使用定时任务定期清理过期数据,比如每隔一段时间遍历 ConcurrentHashMap,判断数据是否过期并移除。
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(() -> {
long currentTime = System.currentTimeMillis();
for (Map.Entry<String, Object> entry : cache.entrySet()) {
String key = entry.getKey();
long insertTime = (long) cache.get(key + "_time");
if (currentTime - insertTime > EXPIRE_TIME) {
cache.remove(key);
cache.remove(key + "_time");
}
}
}, 0, EXPIRE_TIME, TimeUnit.MILLISECONDS);
以上是通过 ConcurrentHashMap 实现类似 Redis 过期时间设置的方式,但需要注意的是,ConcurrentHashMap 是存储在内存中的,如果需要持久化数据或分布式缓存,还需要考虑其他方案
原文地址: http://www.cveoy.top/t/topic/hNzq 著作权归作者所有。请勿转载和采集!