liusuyi
2026-06-01 3496700a5ba18be8ca0590a79e21a867782d1ea9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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();
    }
}