Bläddra i källkod

汤阴二期采集压力数据

1037015548@qq.com 3 veckor sedan
förälder
incheckning
fb3caf2580

+ 145 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/bizmgr/KprTangyinWaterBizFun.java

@@ -0,0 +1,145 @@
+package io.github.pnoker.gateway.bizmgr;
+
+import io.github.pnoker.gateway.dbdao.DBMgrProxy;
+import io.github.pnoker.gateway.dbdao.tangyinSource.service.TangyinPressDataService;
+import io.github.pnoker.gateway.utils.InfulxDbUtil;
+import io.github.pnoker.gateway.utils.InfulxTyDbUtil;
+import org.influxdb.dto.QueryResult;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.text.SimpleDateFormat;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.*;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @ClassName KprTangyinWaterBizFun
+ * @Description: TODO 汤阴二期相关业务功能类
+ * @Author LX
+ * @Date 2025/6/4
+ * @Version V1.0
+ **/
+public class KprTangyinWaterBizFun {
+    private static final Logger log = LoggerFactory.getLogger(KprTangyinWaterBizFun.class);
+
+    public static InfulxTyDbUtil infulxTyDbUtil = null;//infulx工具类对象
+
+    public static TangyinPressDataService getApi(){
+        return DBMgrProxy.getInstance().applyTangyinPressDataService();
+    }
+    private static long formaterUTCnano(LocalDateTime localDateTime){
+        // 转换为 Instant(基于 UTC 时间)
+        Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
+
+        // 获取纳秒时间戳
+        long nanoTimestamp = instant.getEpochSecond() * 1_000_000_000L + instant.getNano();
+        return nanoTimestamp;
+    }
+    //TODO 查询一年的数据调用selectPressCollecation
+    public static void selectOneYear(){
+        log.info("启动时执行一年压力数据操作");
+        log.info("进行中.....");
+        // 当前时间
+        LocalDateTime now = LocalDateTime.now();
+        // 一年前的时间
+        LocalDateTime startDateTime = now.minusYears(1);
+
+        // 创建Map来存储时间范围
+        Map<LocalDateTime, LocalDateTime> timeRanges = new LinkedHashMap<>();
+
+        // 初始化开始时间
+        LocalDateTime currentStart = startDateTime; // 一年前
+        for (int i = 0; i < 12; i++) {
+            // 当前时间段的结束时间:当前月的最后一天 23:59:59
+            LocalDateTime currentEnd = currentStart.plusMonths(1).minusSeconds(1);
+
+            // 将开始和结束时间存储到Map中
+            timeRanges.put(currentStart, currentEnd);
+
+            // 将开始时间推进到下一个月
+            currentStart = currentStart.plusMonths(1);
+        }
+
+        final CountDownLatch latch = new CountDownLatch(timeRanges.keySet().size());
+        for (LocalDateTime startTime:timeRanges.keySet()){
+            new Thread(() -> {
+                long startLong = formaterUTCnano(startTime);
+                long endLong = formaterUTCnano(timeRanges.get(startTime));
+                String queryInfluxdbSql = "SELECT time,dev_id,press_cur FROM WaterMeter WHERE " +
+                        " time >= "+startLong+" and time<="+endLong+" ORDER BY time desc tz('Asia/Shanghai')";
+                log.info(startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))+"---"+
+                        timeRanges.get(startTime).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))+"进行中.....");
+                selectPressCollecation(queryInfluxdbSql);
+                log.info(startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))+"---"+
+                        timeRanges.get(startTime).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))+"已完成");
+                latch.countDown();
+            }).start();
+        }
+        try {
+            latch.await();
+        }catch(Exception ex){
+
+        }
+        log.info("启动时执行一年压力数据操作完成");
+    }
+
+    //TODO 查询压力数据并插入到pgsql数据库
+    public static void selectPressCollecation(String queryInfluxdbSql){
+        try{
+            if(infulxTyDbUtil!=null){
+                log.info("查询压力并插入到pgsql开始,SQL语句:"+queryInfluxdbSql);
+                QueryResult queryResult = infulxTyDbUtil.queryDatabase(queryInfluxdbSql);
+                List<QueryResult.Series> seriesList = queryResult.getResults().get(0).getSeries();
+                if (seriesList != null) {
+                    for (QueryResult.Series series : seriesList) {
+                        List<List<Object>> values = series.getValues();
+                        for (List<Object> value : values) {
+                            try {
+                                // 解析字段
+                                String timeString = (String) value.get(0); // 时间戳
+                                String devId = (String) value.get(1);       // 设备ID
+                                Double pressCur = (Double) value.get(2);    // 当前压力
+
+                                // 解析ISO 8601格式的日期时间
+                                ZonedDateTime zonedDateTime = ZonedDateTime.parse(timeString);
+
+                                // 转换为LocalDateTime(去除时区信息)
+                                LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
+
+                                // 定义目标格式
+                                DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+
+                                // 格式化为目标格式字符串
+                                String formattedDate = localDateTime.format(targetFormatter);
+
+                                // 打印结果
+                                System.out.println("Formatted Date: " + formattedDate + ", Dev ID: " + devId + ", Press Cur: " + pressCur);
+                                //TODO 将数据插入或修改到pgsql
+                                Map<String,Object> map = new HashMap<>();
+                                map.put("collecation_time",formattedDate);
+                                map.put("dev_id",devId);
+                                map.put("press_cur",pressCur);
+                                int resultDb = getApi().insertOrUpdateTbmHourLevel(map);
+                                if(!(resultDb>0)){
+                                    log.error("function selectPressCollecation insertOrUpdate error:"+resultDb);
+                                }
+                            } catch (Exception ex) {
+                                ex.printStackTrace();
+                                log.error("function selectPressCollecation forEach error:"+ex.getLocalizedMessage());
+                            }
+                        }
+                    }
+                }
+                log.info("function selectPressCollecation success:"+queryInfluxdbSql);
+            }
+        }catch (Exception ex){
+            log.error("function selectPressCollecation error:"+ex.getLocalizedMessage());
+        }
+    }
+}

+ 36 - 4
dc3-gateway/src/main/java/io/github/pnoker/gateway/comtool/ScheduleTaskMgr.java

@@ -6,6 +6,7 @@ import io.github.pnoker.gateway.bizmgr.*;
 import io.github.pnoker.gateway.dbdao.DBMgrProxy;
 import io.github.pnoker.gateway.utils.InfulxDbUtil;
 import io.github.pnoker.gateway.utils.InfulxJiangjinDbUtil;
+import io.github.pnoker.gateway.utils.InfulxTyDbUtil;
 import io.github.pnoker.gateway.utils.InfulxZilaishuiDbUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -370,7 +371,7 @@ public class ScheduleTaskMgr {
     /**
      * TODO 自来水相关
      */
-    @Resource(name = "infulxZilaishuiDbUtil")
+    /*@Resource(name = "infulxZilaishuiDbUtil")
     private InfulxZilaishuiDbUtil infulxZilaishuiDbUtil;
 
     //TODO 启动后5秒初始化所有配置参数
@@ -431,7 +432,7 @@ public class ScheduleTaskMgr {
                 .atStartOfDay());
     }
     //TODO 市自来水水位预测相关
-    /*@PostConstruct
+    @PostConstruct
     public void initWaterCollecationReacordAll(){
         new Timer().schedule(new TimerTask() {
             @Override
@@ -461,7 +462,7 @@ public class ScheduleTaskMgr {
         },5000);
     }
     //TODO 每小时的10分执行原始小时液位数据计算
-    @Scheduled(cron = "0 15 * * * *")
+    @Scheduled(cron = "0 * * * * ?")
     public void initYuceLevel(){
         new Timer().schedule(new TimerTask() {
             @Override
@@ -470,7 +471,7 @@ public class ScheduleTaskMgr {
                 KprZilaishuiLevelBizFun.insertForecastData();
             }
         },5000);
-    }*/
+    }
 
     //TODO 市自来水泵数据采集
     @PostConstruct
@@ -504,5 +505,36 @@ public class ScheduleTaskMgr {
                 KprZilaishuiPumpBizFun.initWaterPumpReacordAll(formattedDate);
             }
         },5000);
+    }*/
+
+    /**
+     * TODO 汤阴业务相关
+     */
+    @Resource(name = "infulxTyDbUtil")
+    private InfulxTyDbUtil infulxTyDbUtil;
+
+    //TODO 启动后5秒初始化所有配置参数
+    @PostConstruct
+    public void initTangyinApplication(){
+        new Timer().schedule(new TimerTask() {
+            @Override
+            public void run() {
+                try {
+                    infulxTyDbUtil.initInfluxDataBase();
+                    KprTangyinWaterBizFun.infulxTyDbUtil = infulxTyDbUtil;
+                }catch(Exception ex){
+                    log.error("汤阴启动时初始化配置参数失败:"+ex.getLocalizedMessage());
+                }
+            }
+        },5000);
+    }
+    @PostConstruct
+    public void oneYearInit(){
+        new Timer().schedule(new TimerTask() {
+            @Override
+            public void run() {
+                KprTangyinWaterBizFun.selectOneYear();
+            }
+        },7000);
     }
 }

+ 106 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/config/Child4SourceConfiguration.java

@@ -0,0 +1,106 @@
+package io.github.pnoker.gateway.config;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.mybatis.spring.SqlSessionFactoryBean;
+import org.mybatis.spring.SqlSessionTemplate;
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+
+import javax.annotation.PostConstruct;
+import javax.sql.DataSource;
+
+@Configuration
+@MapperScan(basePackages = "io.github.pnoker.gateway.dbdao.mapper", sqlSessionTemplateRef = "child4SqlSessionTemplate")
+public class Child4SourceConfiguration {
+    @Value("${spring.datasource.child4pg.driver-class-name:}")
+    private String driveClass = "org.postgresql.Driver";
+
+    @Value("${spring.datasource.child4pg.jdbc-url:}")
+    private String url = "";
+
+    @Value("${spring.datasource.child4pg.username:}")
+    private String username = "";
+
+    @Value("${spring.datasource.child4pg.password:}")
+    private String password = "";
+
+    @Value("${spring.datasource.data.maximum-pool-size:200}")
+    private Integer maxPoolSize;
+
+    @Value("${spring.datasource.data.minimum-idle:1}")
+    private Integer minIdle;
+
+    @Value("${spring.datasource.data.connection-test-query:}")
+    private String connectionTestQuery;
+
+    @Value("${spring.datasource.data.max-lifetime:120000}")
+    private Long maxLifetime;
+
+    @Value("${spring.datasource.data.idle-timeout:30000}")
+    private Long idleTimeout;
+
+    @Value("${spring.datasource.data.connection-timeout:30000}")
+    private Long connectionTimeout;
+
+    @Value("${spring.datasource.data.validation-timeout:30000}")
+    private Long validTimeout;
+
+    @Bean(name = "child4Datasource")
+    //@ConfigurationProperties(prefix = "spring.datasource.data")
+    public DataSource mainDataSource() {
+        return new HikariDataSource(getConfig());
+        //return DataSourceBuilder.create().build();
+        //Spring Boot 2.x默认使用HikariCP
+    }
+
+    private HikariConfig getConfig() {
+        HikariConfig hikariConfig = new HikariConfig();
+        hikariConfig.setDriverClassName(driveClass);
+        hikariConfig.setJdbcUrl(url);
+        hikariConfig.setUsername(username);
+        hikariConfig.setPassword(password);
+
+        hikariConfig.setMaximumPoolSize(maxPoolSize);
+        hikariConfig.setMinimumIdle(minIdle);
+        hikariConfig.setConnectionTestQuery(connectionTestQuery);
+        hikariConfig.setMaxLifetime(maxLifetime);
+        hikariConfig.setIdleTimeout(idleTimeout);
+        hikariConfig.setConnectionTimeout(connectionTimeout);
+        hikariConfig.setValidationTimeout(validTimeout);
+        return hikariConfig;
+    }
+
+    @Bean("child4SqlSessionFactory")
+    public SqlSessionFactory child4SqlSessionFactoryBean(@Qualifier("child4Datasource") DataSource dataSource) throws Exception {
+        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
+        sessionFactoryBean.setDataSource(dataSource);
+
+        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
+        configuration.setCallSettersOnNulls(true);       //数据库中字段值为null时也要求返回
+        configuration.setMapUnderscoreToCamelCase(true); //开启驼峰映射
+        configuration.setCacheEnabled(false);
+        sessionFactoryBean.setConfiguration(configuration);
+        return sessionFactoryBean.getObject();
+    }
+
+    @Bean("child4SqlSessionTemplate")
+    public SqlSessionTemplate child4SqlSessionTemplate(@Qualifier("child4SqlSessionFactory") SqlSessionFactory sessionFactory) {
+        return new SqlSessionTemplate(sessionFactory);
+    }
+
+    @Bean(name = "child4DbTransactionManager")
+    public DataSourceTransactionManager child4DbTransactionManager(@Qualifier("child4Datasource") DataSource dataSource){
+        return new DataSourceTransactionManager(dataSource);
+    }
+
+    @PostConstruct
+    public void init(){
+        GlobalData.getInstance().setPostGisValid("org.postgis.DriverWrapper".equals(driveClass));
+    }
+}

+ 5 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/dbdao/DBMgrProxy.java

@@ -3,6 +3,7 @@ package io.github.pnoker.gateway.dbdao;
 import io.github.pnoker.gateway.SpringContextUtil;
 import io.github.pnoker.gateway.dbdao.jiangjinSource.services.JiangjinService;
 import io.github.pnoker.gateway.dbdao.services.intef.*;
+import io.github.pnoker.gateway.dbdao.tangyinSource.service.TangyinPressDataService;
 import io.github.pnoker.gateway.dbdao.zilaishuiSource.service.ZilaishuiRealListService;
 
 /**
@@ -22,6 +23,7 @@ public class DBMgrProxy {
 
     private volatile JiangjinService jiangjinService = null;
     private volatile ZilaishuiRealListService zilaishuiRealListService = null;
+    private volatile TangyinPressDataService tangyinPressDataService= null;
 
     private volatile WaterTapWaterService waterTapWaterService = null;
 
@@ -56,6 +58,8 @@ public class DBMgrProxy {
             zilaishuiRealListService = (ZilaishuiRealListService)SpringContextUtil.getBean(ZilaishuiRealListService.class);
         if (waterTapWaterService == null)
             waterTapWaterService = (WaterTapWaterService)SpringContextUtil.getBean(WaterTapWaterService.class);
+        if (tangyinPressDataService == null)
+            tangyinPressDataService = (TangyinPressDataService)SpringContextUtil.getBean(TangyinPressDataService.class);
     }
 
     public XuChangCustomerWaterConfigService applyXuchangCustomerWaterConfigApi() { return xuchangCustomerWaterConfigService; }
@@ -66,4 +70,5 @@ public class DBMgrProxy {
     public JiangjinService applyJiangjinDbApi() { return jiangjinService; }
     public ZilaishuiRealListService applyZilaishuiDbApi() { return zilaishuiRealListService; }
     public WaterTapWaterService applyWaterTapWaterService() { return waterTapWaterService; }
+    public TangyinPressDataService applyTangyinPressDataService() { return tangyinPressDataService; }
 }

+ 57 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/dbdao/tangyinSource/TangyinPressDataDao.java

@@ -0,0 +1,57 @@
+package io.github.pnoker.gateway.dbdao.tangyinSource;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Repository;
+import org.springframework.util.ObjectUtils;
+
+import javax.sql.DataSource;
+import java.util.Map;
+
+/**
+ * @ClassName TangyinPressDataDao
+ * @Description: TODO
+ * @Author LX
+ * @Date 2025/6/4
+ * @Version V1.0
+ **/
+@Slf4j
+@Repository
+public class TangyinPressDataDao {
+    @Autowired
+    @Qualifier("child4Datasource")
+    private DataSource child4Datasource;
+
+    //TODO 添加或修改日小时预测数据
+    public int insertOrUpdateTbmHourLevel(Map<String,Object> value){
+        try{
+            String sql = "INSERT INTO press_data " +
+                    "(collecation_time,dev_id";
+            if(!ObjectUtils.isEmpty(value.get("press_cur"))){
+                sql +=  " , press_cur ";
+            }
+
+            sql+= " ) VALUES ";
+            sql +=" ( ' ";
+            sql += value.get("collecation_time")+"','"+value.get("dev_id")+"'";
+            if(!ObjectUtils.isEmpty(value.get("press_cur"))){
+                sql +=","+value.get("press_cur");
+            }
+            sql += " )";
+            sql += " ON CONFLICT (collecation_time,dev_id) " +
+                    " DO UPDATE " +
+                    " SET collecation_time =  '"+value.get("collecation_time")+"' " +
+                    " , \"dev_id\" =  '"+value.get("dev_id")+"' ";
+            if(!ObjectUtils.isEmpty(value.get("press_cur"))){
+                sql +=  " , press_cur =  '"+value.get("press_cur")+"' ";
+            }
+            JdbcTemplate pgJdbc = new JdbcTemplate(child4Datasource);
+            Integer resCode = pgJdbc.update(sql);
+            return resCode;
+        }catch(Exception ex){
+            return -1;
+        }
+    }
+}

+ 7 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/dbdao/tangyinSource/service/TangyinPressDataService.java

@@ -0,0 +1,7 @@
+package io.github.pnoker.gateway.dbdao.tangyinSource.service;
+
+import java.util.Map;
+
+public interface TangyinPressDataService {
+    public int insertOrUpdateTbmHourLevel(Map<String,Object> value);
+}

+ 26 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/dbdao/tangyinSource/service/impl/TangyinPressDataServiceImpl.java

@@ -0,0 +1,26 @@
+package io.github.pnoker.gateway.dbdao.tangyinSource.service.impl;
+
+import io.github.pnoker.gateway.dbdao.tangyinSource.TangyinPressDataDao;
+import io.github.pnoker.gateway.dbdao.tangyinSource.service.TangyinPressDataService;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * @ClassName TangyinPressDataServiceImpl
+ * @Description: TODO
+ * @Author LX
+ * @Date 2025/6/4
+ * @Version V1.0
+ **/
+@Service
+public class TangyinPressDataServiceImpl implements TangyinPressDataService{
+    @Resource
+    private TangyinPressDataDao tangyinPressDataDao;
+
+    @Override
+    public int insertOrUpdateTbmHourLevel(Map<String, Object> value) {
+        return tangyinPressDataDao.insertOrUpdateTbmHourLevel(value);
+    }
+}

+ 10 - 10
dc3-gateway/src/main/java/io/github/pnoker/gateway/dbdao/zilaishuiSource/ZilaishuiRealListDao.java

@@ -352,16 +352,16 @@ public class ZilaishuiRealListDao {
     }
 
     public void insertDailyData() {
-        String sql = "INSERT INTO tb_m_hourlevel(device_code, date, hour, hour_actual_water_level) " +
-                "SELECT FF.device_code, FF.for_date, FF.for_hour, FF.data " +
-                "FROM (SELECT device_code, " +
-                "CAST(value AS NUMERIC(18, 2)) as data, " +
-                "TO_DATE(time, 'yyyy-mm-dd HH24:MI:SS') AS for_date, " +
-                "TO_TIMESTAMP(time, 'yyyy-mm-dd HH24:MI:SS')::time(6) AS for_hour " +
-                "FROM water_level_record_all " +
-                "WHERE TO_DATE(time, 'yyyy-mm-dd HH24:MI:SS') >= (CURRENT_DATE - INTERVAL '1 day')) FF " +
-                "ON CONFLICT (device_code, date, hour) " +
-                "DO UPDATE SET hour_actual_water_level = excluded.hour_actual_water_level;";
+        String sql = "INSERT INTO tb_m_hourlevel(device_code, date, hour, hour_actual_water_level) \n" +
+                "SELECT FF.device_code, FF.for_date, FF.for_hour, FF.data \n" +
+                "FROM (SELECT device_code, \n" +
+                "             CAST(value AS NUMERIC(18, 2)) as data, \n" +
+                "             TO_DATE(time, 'yyyy-mm-dd HH24:MI:SS') AS for_date, \n" +
+                "             TO_TIMESTAMP(time, 'yyyy-mm-dd HH24:MI:SS')::time(6) AS for_hour \n" +
+                "      FROM water_level_record_all \n" +
+                "      WHERE TO_DATE(time, 'yyyy-mm-dd HH24:MI:SS') >= (CURRENT_DATE - INTERVAL '1 day')) FF \n" +
+                "ON CONFLICT (device_code, date, hour) \n" +
+                "DO UPDATE SET hour_actual_water_level = excluded.hour_actual_water_level";
         JdbcTemplate pgJdbc = new JdbcTemplate(child2DataSource);
         pgJdbc.update(sql);
     }

+ 69 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/utils/InfulxTyDbUtil.java

@@ -0,0 +1,69 @@
+package io.github.pnoker.gateway.utils;
+
+import io.github.pnoker.gateway.comtool.ResponseCode;
+import org.influxdb.InfluxDB;
+import org.influxdb.InfluxDBFactory;
+import org.influxdb.dto.BatchPoints;
+import org.influxdb.dto.Point;
+import org.influxdb.dto.Query;
+import org.influxdb.dto.QueryResult;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+/**
+ * @ClassName InfulxDbUtil
+ * @Description: TODO influxDb连接工具类
+ * @Author LX
+ * @Date 2024/9/3
+ * @Version V1.0
+ **/
+@Component("infulxTyDbUtil")
+public class InfulxTyDbUtil {
+    @Value("${tangyin.inluxdb.serverUrl:}")
+    private String serverUrl = ""; // InfluxDB 服务器地址
+
+    @Value("${tangyin.inluxdb.database:}")
+    private String database = ""; // 数据库名称
+
+    private InfluxDB influxDB = null;
+
+    public void initInfluxDataBase() {
+        // 不需要用户名和密码进行连接
+        influxDB = InfluxDBFactory.connect(serverUrl);
+        // 创建数据库
+        influxDB.query(new Query("CREATE DATABASE " + database));
+
+        // 设置要使用的数据库
+        influxDB.setDatabase(database);
+    }
+
+    public ResponseCode insert(Point point) {
+        try {
+            influxDB.write(point);
+            return ResponseCode.RESULT_NORMAL;
+        } catch (Exception ex) {
+            return ResponseCode.BUSINESS_DB_REQ_FAILED;
+        }
+    }
+
+    public ResponseCode insertBatch(BatchPoints point) {
+        try {
+            influxDB.write(point);
+            return ResponseCode.RESULT_NORMAL;
+        } catch (Exception ex) {
+            return ResponseCode.BUSINESS_DB_REQ_FAILED;
+        }
+    }
+
+    public QueryResult queryDatabase(String sqlQuery) {
+        try {
+            Query query = new Query(sqlQuery, database);
+            QueryResult result = influxDB.query(query);
+            return result;
+        } catch (Exception ex) {
+            // 处理异常
+            ex.printStackTrace();
+            return null;
+        }
+    }
+}

+ 14 - 53
dc3-gateway/src/main/java/io/github/pnoker/gateway/utils/TestUtil.java

@@ -10,8 +10,7 @@ import org.influxdb.dto.QueryResult;
 import java.text.SimpleDateFormat;
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
-import java.util.Date;
-import java.util.List;
+import java.util.*;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -24,56 +23,18 @@ import java.util.concurrent.TimeUnit;
 public class TestUtil {
     private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     public static void main(String[] args) throws Exception{
-        // 获取当前时间的整时0分0秒,这里的时主要还是定时器的执行任务时间去控制
-        LocalDateTime now = LocalDateTime.now().withMinute(0).withSecond(0);
-
-        // 使用提取的值构造新的LocalDateTime对象
-        LocalDateTime firstDayOfMonthWithCurrentTime = now.minusHours(3);
-        System.out.println(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
-        System.out.println(firstDayOfMonthWithCurrentTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
-        JSONObject jsonObject = new JSONObject();
-        jsonObject.put("time","2024-09-03 09:54:00");
-        Date timeStr = dateFormat.parse(jsonObject.getString("time"));
-        // 连接到 InfluxDB
-        String serverURL = "http://localhost:8086"; // InfluxDB 服务器地址
-        String username = "admin"; // InfluxDB 用户名
-        String password = "yourpassword"; // InfluxDB 密码
-        String database = "mydb"; // 数据库名称
-
-        InfluxDB influxDB = InfluxDBFactory.connect(serverURL, username, password);
-
-        try {
-            // 创建数据库
-            influxDB.query(new Query("CREATE DATABASE " + database));
-
-            // 设置要使用的数据库
-            influxDB.setDatabase(database);
-
-            // 写入数据
-            Point point = Point.measurement("cpu")
-                    .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
-                    .addField("usage", 0.64)
-                    .addField("host", "server01")
-                    .build();
-            influxDB.write(point);
-
-            // 查询数据
-            Query query = new Query("SELECT * FROM cpu", database);
-            QueryResult result = influxDB.query(query);
-
-            // 处理查询结果
-            for (QueryResult.Result res : result.getResults()) {
-                for (QueryResult.Series series : res.getSeries()) {
-                    System.out.println("Series: " + series.getName());
-                    System.out.println("Columns: " + series.getColumns());
-                    for (List<Object> values : series.getValues()) {
-                        System.out.println("Values: " + values);
-                    }
-                }
-            }
-        } finally {
-            // 关闭连接
-            influxDB.close();
-        }
+        // 转换ISO时间戳为目标格式
+        // 转换为毫秒时间戳
+        long nanoTimestamp = 1640999400000000000L;
+        long milliTimestamp = TimeUnit.MILLISECONDS.convert(nanoTimestamp, TimeUnit.NANOSECONDS);
+
+        // 创建Date对象
+        Date date = new Date(milliTimestamp);
+
+        // 格式化为目标格式
+        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        targetFormat.setTimeZone(java.util.TimeZone.getTimeZone("Asia/Shanghai")); // 转换为上海时区
+        String formattedDate = targetFormat.format(date);
+        System.out.println(formattedDate);
     }
 }

+ 18 - 1
dc3-gateway/src/main/resources/application.yml

@@ -167,6 +167,11 @@ spring:
         username: postgres
         password: ygt.23417.postgres
 #        password: kpr.23417.postgres
+      child4pg:
+        driver-class-name: org.postgis.DriverWrapper
+        jdbc-url: jdbc:postgresql_postGIS://221.176.189.184:5432/tangyin_press?useSSL=false&useAffectedRows=false&allowMultiQueries=true
+        username: postgres
+        password: kpr.23417.postgres
   jpa:
     show-sql: false
 
@@ -261,4 +266,16 @@ zilaishui:
   inluxdb:
     database: iot_test
 #    database: iot
-    serverUrl: http://10.101.5.201:8086
+    serverUrl: http://10.101.5.201:8086
+
+#汤阴二期相关配置
+tangyin:
+#influxdb相关配置
+  inluxdb:
+      database: iot_test
+      serverUrl: http://10.101.16.13:8086
+#    database: iot_test
+#    database: iot
+#    serverUrl: http://221.176.189.184:8086
+#    username: kpr
+#    password: kpr.2024dy.influxdb