liusuyi
2026-05-30 f4f4fc53260eb67483dce406a963628273786a61
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
package com.ard.work.device.camera.service;
 
import com.ard.work.device.camera.domain.PtzParamDTO;
import org.springframework.stereotype.Component;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * ptz缓存管理器
 *
 * @author 刘苏义
 * @date 2026-03-20
 */
@Component
public class PtzCacheManager {
 
    /** Key: cameraId_chanNo, Value: 最新PTZ数据(自带 updateTime) */
    private final ConcurrentHashMap<String, PtzParamDTO> ptzDataMap = new ConcurrentHashMap<>();
 
    public void updatePtzData(String key, PtzParamDTO data) {
        if (data == null) return;
        data.setUpdateTime(System.currentTimeMillis());
        ptzDataMap.put(key, data);
    }
 
    public PtzParamDTO getPtzData(String key) {
        return ptzDataMap.get(key);
    }
 
    /** 获取所有未过期数据快照 */
    public List<PtzParamDTO> getAllValidData(long timeoutMs) {
        long now = System.currentTimeMillis();
        Collection<PtzParamDTO> values = ptzDataMap.values();
        List<PtzParamDTO> result = new ArrayList<>(values.size());
        for (PtzParamDTO dto : values) {
            if (now - dto.getUpdateTime() < timeoutMs) {
                result.add(dto);
            }
        }
        return result;
    }
 
    public void removeData(String key) {
        ptzDataMap.remove(key);
    }
 
    /** 清理过期数据,返回清理条数 */
    public int evictStale(long timeoutMs) {
        long now = System.currentTimeMillis();
        int[] count = {0};
        ptzDataMap.entrySet().removeIf(e -> {
            if (now - e.getValue().getUpdateTime() > timeoutMs) {
                count[0]++;
                return true;
            }
            return false;
        });
        return count[0];
    }
}