wenminjie
2026-07-17 cd44290dc230d64ef9e382777b9722e81a661570
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package com.ruoyi.web.controller.service;
 
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.domain.SysVisitorRecord;
import com.ruoyi.system.mapper.SysVisitorRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
 
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class SysVisitorRecordService extends ServiceImpl<SysVisitorRecordMapper, SysVisitorRecord> {
 
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
 
    private static final String REDIS_KEY_PREFIX = "visitor:expire:";
 
    /**
     * 登记访客时设置 Redis 过期 Key
     */
    public void registerVisitor(SysVisitorRecord record) {
 
        // 2. 设置 Redis 过期 Key
        setRedisExpireKey(record);
 
        log.info("访客 {} 登记成功,有效期至:{}", record.getRecordId(), record.getValidEndTime());
    }
 
    /**
     * 设置 Redis 过期 Key
     */
    private void setRedisExpireKey(SysVisitorRecord record) {
        Date now = new Date();
        Date validEndTime = record.getValidEndTime();
 
        // 如果有效期结束时间小于当前时间,直接签离
        if (validEndTime.before(now)) {
            log.warn("访客记录 {} 已超期,直接签离", record.getRecordId());
            autoSignOut(record);
            return;
        }
 
        // 计算过期时间(毫秒)
        long expireTime = validEndTime.getTime() - now.getTime();
        String key = REDIS_KEY_PREFIX + record.getRecordId();
 
        // 设置 Redis Key,过期时间为 validEndTime
        redisTemplate.opsForValue().set(
                key,
                record.getRecordId().toString(),
                expireTime,
                TimeUnit.MILLISECONDS
        );
 
        log.info("设置Redis过期Key成功,Key:{},过期时间:{} 毫秒", key, expireTime);
    }
 
    /**
     * 根据记录ID自动签离(由Redis过期事件触发)
     */
    @Transactional
    public void autoSignOutByRecordId(Long recordId) {
        try {
            // 1. 查询记录
            SysVisitorRecord record = this.getById(recordId);
            if (record == null) {
                log.warn("访客记录不存在,ID:{}", recordId);
                return;
            }
 
            // 2. 检查状态(只有 VISITING 状态才处理)
            if (!"VISITING".equals(record.getStatus())) {
                log.info("访客记录 {} 状态为 {},无需处理", recordId, record.getStatus());
                return;
            }
 
            // 3. 检查是否真的超期(双重检查)
            Date now = new Date();
            if (!record.getValidEndTime().before(now)) {
                log.info("访客记录 {} 有效期未结束,无需签离", recordId);
                return;
            }
 
            // 4. 执行签离
            autoSignOut(record);
 
            // 5. 删除 Redis Key(防止重复触发)
            redisTemplate.delete(REDIS_KEY_PREFIX + recordId);
 
            log.info("Redis过期触发签离成功,记录ID:{},签离时间:{}", recordId, now);
 
        } catch (Exception e) {
            log.error("自动签离失败,记录ID:{}", recordId, e);
            throw e;
        }
    }
 
    /**
     * 执行自动签离
     */
    private void autoSignOut(SysVisitorRecord record) {
        Date now = new Date();
        record.setStatus("PENDING_CONFIRM");
        record.setSignTime(now);
        record.setRemark("逾期滞留,等待确认");
        record.setUpdateTime(now);
        this.updateById(record);
    }
 
    /**
     * 更新访客记录(并重置 Redis 过期时间)
     */
    public boolean updateVisitor(SysVisitorRecord record) {
        // 1. 更新记录
        boolean updated = this.updateById(record);
        if (!updated) {
            return false;
        }
 
        // 2. 如果状态变更为 VISITING,重新设置过期时间
        if ("VISITING".equals(record.getStatus())) {
            setRedisExpireKey(record);
        }
 
        // 3. 如果已签离,删除 Redis Key
        if ("SIGNED_OUT".equals(record.getStatus()) ||
                "OVERDUE_AUTO_SIGNED_OUT".equals(record.getStatus())) {
            redisTemplate.delete(REDIS_KEY_PREFIX + record.getRecordId());
        }
 
        return true;
    }
 
    /**
     * 兜底方案:启动时检查所有超期记录
     */
    @Transactional
    public int checkAndAutoSignOutOnStartup() {
        // 查询所有超期记录
        LambdaQueryWrapper<SysVisitorRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysVisitorRecord::getStatus, "VISITING")
                .lt(SysVisitorRecord::getValidEndTime, new Date());
 
        List<SysVisitorRecord> overdueRecords = this.list(queryWrapper);
 
        if (CollUtil.isEmpty(overdueRecords)) {
            log.info("启动检查:没有超期访客记录");
            return 0;
        }
 
        log.info("启动检查:发现 {} 条超期记录,开始处理", overdueRecords.size());
 
        Date now = new Date();
        int count = 0;
        for (SysVisitorRecord record : overdueRecords) {
            try {
                record.setStatus("OVERDUE_AUTO_SIGNED_OUT");
                record.setSignTime(now);
                record.setRemark("系统自动签离(启动时检查)");
                record.setUpdateTime(now);
                this.updateById(record);
 
                // 删除 Redis Key
                redisTemplate.delete(REDIS_KEY_PREFIX + record.getRecordId());
                count++;
            } catch (Exception e) {
                log.error("启动检查处理记录失败,ID:{}", record.getRecordId(), e);
            }
        }
 
        log.info("启动检查完成,处理 {} 条超期记录", count);
        return count;
    }
}