Просмотр исходного кода

设备定时从其他数据库同步数据

ouyj 6 месяцев назад
Родитель
Сommit
98bb5568ad

+ 11 - 2
ygtx-admin/src/main/resources/application-dev.yml

@@ -6,7 +6,7 @@ spring:
         druid:
             # 主库数据源
             master:
-                url: jdbc:mysql://localhost:3306/worklog?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
+                url: jdbc:mysql://localhost:3306/ygtx_gxt?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
                 username: root
                 password: 123456
             # 从库数据源
@@ -16,6 +16,15 @@ spring:
                 url:
                 username:
                 password:
+            # 源数据库数据源(用于设备同步)
+            source:
+                url: jdbc:mysql://localhost:3306/equipment_source?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
+                username: root
+                password: 123456
+                initialSize: 5
+                minIdle: 5
+                maxActive: 20
+                maxWait: 60000
             # 初始连接数
             initialSize: 5
             # 最小连接池数量
@@ -58,4 +67,4 @@ spring:
                     merge-sql: true
                 wall:
                     config:
-                        multi-statement-allow: true
+                        multi-statement-allow: true

+ 9 - 0
ygtx-admin/src/main/resources/application-gxt.yml

@@ -16,6 +16,15 @@ spring:
                 url:
                 username:
                 password:
+            # 源数据库数据源(用于设备同步)
+            source:
+                url: jdbc:mysql://222.243.138.146:8712/equipment_source?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
+                username: root
+                password: 11rrRRvv90)*9&FuuI}{
+                initialSize: 5
+                minIdle: 5
+                maxActive: 20
+                maxWait: 60000
             # 初始连接数
             initialSize: 5
             # 最小连接池数量

+ 1 - 1
ygtx-common/src/main/java/com/ygtx/common/constant/Constants.java

@@ -163,7 +163,7 @@ public class Constants
     /**
      * 定时任务白名单配置(仅允许访问的包名,如其他需要可以自行添加)
      */
-    public static final String[] JOB_WHITELIST_STR = { "com.ygtx.quartz.task" };
+    public static final String[] JOB_WHITELIST_STR = { "com.ygtx.quartz.task","com.ygtx.gxt.task" };
 
     /**
      * 定时任务违规的字符

+ 27 - 0
ygtx-gxt/src/main/java/com/ygtx/gxt/conf/SourceDataSourceConfig.java

@@ -0,0 +1,27 @@
+package com.ygtx.gxt.conf;
+
+import com.alibaba.druid.pool.DruidDataSource;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import javax.sql.DataSource;
+
+/**
+ * 源数据库数据源配置
+ * 用于设备同步任务从其他数据库获取数据
+ */
+@Configuration
+public class SourceDataSourceConfig {
+
+    /**
+     * 源数据库数据源
+     * 
+     * @return DataSource 数据源
+     */
+    @Bean(name = "sourceDataSource")
+    @ConfigurationProperties(prefix = "spring.datasource.druid.source")
+    public DataSource sourceDataSource() {
+        return new DruidDataSource();
+    }
+}

+ 181 - 0
ygtx-gxt/src/main/java/com/ygtx/gxt/task/EquipmentSyncTask.java

@@ -0,0 +1,181 @@
+package com.ygtx.gxt.task;
+
+import com.ygtx.common.utils.DateUtils;
+import com.ygtx.common.utils.StringUtils;
+import com.ygtx.gxt.domain.GxtEquipment;
+import com.ygtx.gxt.mapper.GxtEquipmentMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import javax.sql.DataSource;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+@EnableScheduling
+@Component("equipmentSyncTask")
+public class EquipmentSyncTask {
+    
+    private static final Logger log = LoggerFactory.getLogger(EquipmentSyncTask.class);
+
+    @Autowired
+    private GxtEquipmentMapper gxtEquipmentMapper;
+
+    @Autowired
+    @Qualifier("sourceDataSource")
+    private DataSource sourceDataSource;
+    
+    /**
+     * 定时同步设备数据
+     * 每天凌晨2点执行一次同步任务
+     */
+    //@Scheduled(cron = "0 0 2 * * ?")
+    public void syncEquipment() {
+        log.info("设备同步任务开始执行...");
+        
+        Connection conn = null;
+        PreparedStatement stmt = null;
+        ResultSet rs = null;
+        
+        try {
+            // 获取源数据库连接
+            conn = sourceDataSource.getConnection();
+            
+            // 记录连接的数据库信息
+            DatabaseMetaData metaData = conn.getMetaData();
+            // 查询源数据库中的设备数据
+            String sql = "SELECT equipment_code, maintenance_center, station, brand, model FROM gxt_equipment";
+            stmt = conn.prepareStatement(sql);
+            rs = stmt.executeQuery();
+            
+            // 存储从源数据库查询到的设备数据
+            List<GxtEquipment> sourceEquipmentList = new ArrayList<>();
+            
+            int count = 0;
+            while (rs.next()) {
+                GxtEquipment equipment = new GxtEquipment();
+                equipment.setEquipmentCode(rs.getString("equipment_code"));
+                equipment.setMaintenanceCenter(rs.getString("maintenance_center"));
+                equipment.setStation(rs.getString("station"));
+                equipment.setBrand(rs.getString("brand"));
+                equipment.setModel(rs.getString("model"));
+                
+                // 设置默认值
+                equipment.setEquipmentType("1"); // 默认设置为风机
+                equipment.setStatus("1"); // 默认设置为正常状态
+                
+                sourceEquipmentList.add(equipment);
+                count++;
+            }
+            
+            log.info("从源数据库查询到 {} 条设备数据", sourceEquipmentList.size());
+            
+            // 同步数据到当前系统数据库
+            syncDataToTargetDatabase(sourceEquipmentList);
+            
+            log.info("设备同步任务执行完成,共同步 {} 条数据", sourceEquipmentList.size());
+        } catch (Exception e) {
+            log.error("设备同步任务执行失败:", e);
+        } finally {
+            // 关闭资源
+            closeResources(rs, stmt, conn);
+        }
+    }
+    
+    /**
+     * 同步数据到目标数据库
+     * 
+     * @param sourceEquipmentList 源设备数据列表
+     */
+    private void syncDataToTargetDatabase(List<GxtEquipment> sourceEquipmentList) {
+        if (sourceEquipmentList == null || sourceEquipmentList.isEmpty()) {
+            log.info("没有需要同步的设备数据");
+            return;
+        }
+        
+        int successCount = 0;
+        int updateCount = 0;
+        int insertCount = 0;
+        
+        for (GxtEquipment sourceEquipment : sourceEquipmentList) {
+            try {
+                // 检查设备是否已存在
+                GxtEquipment existingEquipment = gxtEquipmentMapper.selectGxtEquipmentByEquipmentCode(
+                    sourceEquipment.getEquipmentCode());
+                
+                if (existingEquipment != null) {
+                    // 更新现有设备信息
+                    sourceEquipment.setEquipmentId(existingEquipment.getEquipmentId());
+                    sourceEquipment.setUpdateTime(DateUtils.getNowDate());
+                    gxtEquipmentMapper.updateGxtEquipment(sourceEquipment);
+                    updateCount++;
+                    log.debug("更新设备: {}", sourceEquipment.getEquipmentCode());
+                } else {
+                    // 新增设备信息
+                    sourceEquipment.setCreateTime(DateUtils.getNowDate());
+                    gxtEquipmentMapper.insertGxtEquipment(sourceEquipment);
+                    insertCount++;
+                    log.debug("新增设备: {}", sourceEquipment.getEquipmentCode());
+                }
+                successCount++;
+            } catch (Exception e) {
+                log.error("同步设备数据失败,风机编号:{},错误信息:{}", 
+                    sourceEquipment.getEquipmentCode(), e.getMessage(), e);
+            }
+        }
+        
+        log.info("数据同步完成:成功同步 {} 条数据,新增 {} 条,更新 {} 条", 
+            successCount, insertCount, updateCount);
+    }
+    
+    /**
+     * 关闭数据库资源
+     * 
+     * @param rs ResultSet
+     * @param stmt PreparedStatement
+     * @param conn Connection
+     */
+    private void closeResources(ResultSet rs, PreparedStatement stmt, Connection conn) {
+        if (rs != null) {
+            try {
+                rs.close();
+            } catch (SQLException e) {
+                log.error("关闭ResultSet失败:", e);
+            }
+        }
+        
+        if (stmt != null) {
+            try {
+                stmt.close();
+            } catch (SQLException e) {
+                log.error("关闭PreparedStatement失败:", e);
+            }
+        }
+        
+        if (conn != null) {
+            try {
+                conn.close();
+            } catch (SQLException e) {
+                log.error("关闭Connection失败:", e);
+            }
+        }
+    }
+    
+    /**
+     * 测试方法:手动触发设备同步任务
+     */
+    public void testSyncEquipment() {
+        log.info("手动触发设备同步任务开始执行...");
+        syncEquipment();
+        log.info("手动触发设备同步任务执行完成。");
+    }
+}