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 wrapper = new LambdaQueryWrapper<>(); wrapper.orderByDesc(PointData::getTime); wrapper.last("LIMIT 5"); List 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; } } } } }