#
Junjie
9 小时以前 cbb00d4729243e4949b3c921fc2f94cb03ca8aaa
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
package com.zy.core.thread.support;
 
import com.zy.common.utils.RedisUtil;
 
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
 
public class RecentStationArrivalTracker {
 
    static final long DEFAULT_RETAIN_MS = 10_000L;
    static final String KEY_PREFIX = "station_recent_arrival_";
 
    private final RedisUtil redisUtil;
    private final long retainSeconds;
    private final Map<Integer, Integer> lastLoadedTaskByStation = new ConcurrentHashMap<>();
 
    public RecentStationArrivalTracker(RedisUtil redisUtil) {
        this(redisUtil, DEFAULT_RETAIN_MS);
    }
 
    public RecentStationArrivalTracker(RedisUtil redisUtil, long retainMs) {
        this.redisUtil = redisUtil;
        long effectiveRetainMs = retainMs <= 0L ? DEFAULT_RETAIN_MS : retainMs;
        this.retainSeconds = Math.max(1L, (long) Math.ceil(effectiveRetainMs / 1000d));
    }
 
    public void observe(Integer stationId, Integer taskNo, boolean loading) {
        if (stationId == null || stationId <= 0) {
            return;
        }
        if (!loading || taskNo == null || taskNo <= 0) {
            lastLoadedTaskByStation.remove(stationId);
            return;
        }
        Integer previousTaskNo = lastLoadedTaskByStation.put(stationId, taskNo);
        if (Objects.equals(previousTaskNo, taskNo) || redisUtil == null) {
            return;
        }
        redisUtil.set(buildKey(stationId, taskNo), "1", retainSeconds);
    }
 
    public boolean hasRecentArrival(Integer stationId, Integer taskNo) {
        if (redisUtil == null) {
            return false;
        }
        String key = buildKey(stationId, taskNo);
        return key != null && redisUtil.get(key) != null;
    }
 
    private String buildKey(Integer stationId, Integer taskNo) {
        if (stationId == null || stationId <= 0 || taskNo == null || taskNo <= 0) {
            return null;
        }
        return KEY_PREFIX + stationId + "_" + taskNo;
    }
}