package com.ard.work.sdk.zlxd.cache;
|
|
import lombok.extern.slf4j.Slf4j;
|
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.TimeUnit;
|
|
/**
|
* 录像会话缓存 (轻量级优化版)
|
* 增加了过期时间检查和监控日志
|
*
|
* @author 刘苏义
|
* @date 2024/10/24 8:55
|
*/
|
@Slf4j
|
public class RecordSessionCache {
|
|
// 内部类用于存储带时间的对象
|
private static class CacheObject {
|
String sessionId;
|
long expireTime; // 过期时间戳
|
|
public CacheObject(String sessionId, long ttlMillis) {
|
this.sessionId = sessionId;
|
this.expireTime = System.currentTimeMillis() + ttlMillis;
|
}
|
|
boolean isExpired() {
|
return System.currentTimeMillis() > expireTime;
|
}
|
}
|
|
private static final ConcurrentHashMap<String, CacheObject> cache = new ConcurrentHashMap<>();
|
|
// 默认过期时间:24小时 (防止录像任务异常导致内存泄露)
|
private static final long DEFAULT_TTL = TimeUnit.HOURS.toMillis(24);
|
|
/**
|
* 存储数据
|
*/
|
public static void put(String key, String sessionId) {
|
cache.put(key, new CacheObject(sessionId, DEFAULT_TTL));
|
log.debug("录像会话已缓存: key={}, sessionId={}, 过期时间={}ms", key, sessionId, DEFAULT_TTL);
|
}
|
|
/**
|
* 获取数据 (如果过期则自动删除并返回null)
|
*/
|
public static String get(String key) {
|
CacheObject obj = cache.get(key);
|
if (obj == null) {
|
return null;
|
}
|
|
// 检查是否过期
|
if (obj.isExpired()) {
|
cache.remove(key); // 懒删除
|
log.warn("录像会话已过期并移除: key={}", key);
|
return null;
|
}
|
|
return obj.sessionId;
|
}
|
|
/**
|
* 移除数据
|
* @return 返回被移除的 sessionId,如果不存在则返回 null
|
*/
|
public static String remove(String key) {
|
CacheObject removed = cache.remove(key);
|
if (removed != null) {
|
log.info("录像会话已移除: key={}, sessionId={}", key, removed.sessionId);
|
return removed.sessionId;
|
}
|
return null;
|
}
|
|
/**
|
* 获取当前活跃录像数量 (用于监控)
|
*/
|
public static int size() {
|
return cache.size();
|
}
|
}
|