广丰卷烟厂数采质量分析系统
zhuguifei
2026-03-02 974c7aa4010d77bb410b99931b4435d5442deb4b
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
package com.shlb.timescaledbutils;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shlb.timescaledbutils.entity.PointData;
import com.shlb.timescaledbutils.service.IPointDataService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
 
import java.util.List;
import java.util.concurrent.TimeUnit;
 
@SpringBootTest
@Slf4j
class PostgresDataMonitorTest {
 
    @Autowired
    private IPointDataService pointDataService;
 
    /**
     * 监控数据库数据
     * 每5秒查询一次最新的5条数据和总条数
     */
    @Test
    void monitorData() {
        log.info("=== 开始监控 PostgreSQL 数据变化 (按 Ctrl+C 停止) ===");
        
        while (true) {
            try {
                // 记录开始时间
                long start = System.currentTimeMillis();
 
                // 查询总条数
                long count = pointDataService.count();
                
                // 查询最新的 5 条数据 (使用 LIMIT 5 避免全表扫描)
                LambdaQueryWrapper<PointData> wrapper = new LambdaQueryWrapper<>();
                wrapper.orderByDesc(PointData::getTime);
                wrapper.last("LIMIT 5");
                
                List<PointData> latestData = pointDataService.list(wrapper);
 
                // 打印结果
                log.info("--------------------------------------------------");
                log.info("当前时间: {}", new java.util.Date());
                log.info("数据库总条数: {}", count);
                log.info("最新 5 条数据:");
                if (latestData.isEmpty()) {
                    log.info("  (暂无数据)");
                } else {
                    for (PointData data : latestData) {
                        log.info("  {}", data);
                    }
                }
                log.info("--------------------------------------------------");
 
                // 计算休眠时间
                long elapsed = System.currentTimeMillis() - start;
                long sleepTime = 5000 - elapsed;
                if (sleepTime > 0) {
                    TimeUnit.MILLISECONDS.sleep(sleepTime);
                }
 
            } catch (InterruptedException e) {
                log.warn("监控任务被中断");
                Thread.currentThread().interrupt();
                break;
            } catch (Exception e) {
                log.error("查询数据异常", e);
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }
    }
}