推送数据
This commit is contained in:
@@ -68,6 +68,24 @@
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- 现场外部库可能是 Oracle / SQL Server,驱动随包提供,连接信息仍从配置表读取 -->
|
||||
<dependency>
|
||||
<groupId>com.oracle.database.jdbc</groupId>
|
||||
<artifactId>ojdbc11</artifactId>
|
||||
<version>23.4.0.24.05</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- 南昌总库汇总用 Elasticsearch。连不上时开发配置可改走本地表,避免拖垮已有业务。 -->
|
||||
<dependency>
|
||||
<groupId>co.elastic.clients</groupId>
|
||||
<artifactId>elasticsearch-java</artifactId>
|
||||
<version>8.13.4</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 连接池 -->
|
||||
<dependency>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.banben.config;
|
||||
|
||||
import com.banben.modules.auth.interceptor.AuthInterceptor;
|
||||
import com.banben.modules.synchub.config.HubTokenInterceptor;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
@@ -22,6 +23,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
private final AuthInterceptor authInterceptor;
|
||||
private final HubTokenInterceptor hubTokenInterceptor;
|
||||
|
||||
/**
|
||||
* 跨域配置。
|
||||
@@ -46,6 +48,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
* <li>{@code /api/auth/logout} —— 登出由前端清令牌,网络异常时也应能调用</li>
|
||||
* <li>{@code /swagger-ui/**}、{@code /v3/api-docs/**} —— 接口文档</li>
|
||||
* <li>{@code /actuator/**} —— 健康检查(容器探针需要)</li>
|
||||
* <li>{@code /api/hub/**} —— 节点与总库互调用同步口令,不用用户登录令牌</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Override
|
||||
@@ -58,7 +61,10 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
"/api/auth/logout",
|
||||
"/swagger-ui/**",
|
||||
"/v3/api-docs/**",
|
||||
"/actuator/**"
|
||||
"/actuator/**",
|
||||
"/api/hub/**"
|
||||
);
|
||||
registry.addInterceptor(hubTokenInterceptor)
|
||||
.addPathPatterns("/api/hub/**");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ public final class NavMenus {
|
||||
"analysis",
|
||||
"resource",
|
||||
"collect",
|
||||
"sync",
|
||||
"governance",
|
||||
"admin"
|
||||
);
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.banben.modules.sync;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
/**
|
||||
* 打开 Spring 定时调度,供同步任务按配置里的 cron 执行。
|
||||
*/
|
||||
@Configuration
|
||||
@EnableScheduling
|
||||
public class SyncScheduleConfig {
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.banben.modules.sync;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.banben.modules.sync.entity.SyncTask;
|
||||
import com.banben.modules.sync.mapper.SyncTaskMapper;
|
||||
import com.banben.modules.sync.service.SyncService;
|
||||
import com.banben.modules.sync.support.SyncRunner;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.scheduling.support.CronExpression;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 每 30 秒看一次已启用定时的任务。cron 存在任务配置里,改完不用重启。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class SyncScheduler {
|
||||
|
||||
private final SyncTaskMapper taskMapper;
|
||||
private final SyncService syncService;
|
||||
private final SyncRunner syncRunner;
|
||||
|
||||
@Scheduled(initialDelay = 20000, fixedDelay = 30000)
|
||||
public void tick() {
|
||||
List<SyncTask> tasks = taskMapper.selectList(new LambdaQueryWrapper<SyncTask>()
|
||||
.eq(SyncTask::getEnabled, 1)
|
||||
.eq(SyncTask::getScheduleEnabled, 1));
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
for (SyncTask task : tasks) {
|
||||
if (task.getCronExpr() == null || task.getCronExpr().isBlank() || syncRunner.isRunning(task.getId())) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
CronExpression cron = CronExpression.parse(task.getCronExpr().trim());
|
||||
LocalDateTime base = task.getLastScheduleTime() != null
|
||||
? task.getLastScheduleTime()
|
||||
: (task.getCreateTime() == null ? now.minusMinutes(1) : task.getCreateTime());
|
||||
LocalDateTime next = cron.next(base);
|
||||
if (next != null && !next.isAfter(now)) {
|
||||
task.setLastScheduleTime(now);
|
||||
taskMapper.updateById(task);
|
||||
syncService.runTask(task.getId(), "SCHEDULE");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("定时同步任务 {} 未触发:{}", task.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.banben.modules.sync;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 同步相关表自举。开发库和现场库都可能没有这些表,启动时缺了就建,已有数据不动。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class SyncTableInitializer {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
public SyncTableInitializer(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void init() {
|
||||
try {
|
||||
jdbcTemplate.execute(
|
||||
"CREATE TABLE IF NOT EXISTS sync_datasource ("
|
||||
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||
+ "name VARCHAR(128) NOT NULL, "
|
||||
+ "db_type VARCHAR(32) NOT NULL, "
|
||||
+ "host VARCHAR(256) NOT NULL, "
|
||||
+ "port INTEGER NOT NULL, "
|
||||
+ "db_name VARCHAR(128) NOT NULL, "
|
||||
+ "username VARCHAR(128) NOT NULL, "
|
||||
+ "password VARCHAR(256), "
|
||||
+ "jdbc_params VARCHAR(1000), "
|
||||
+ "enabled SMALLINT DEFAULT 1, "
|
||||
+ "remark VARCHAR(500), "
|
||||
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
|
||||
+ "update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
|
||||
+ "deleted SMALLINT DEFAULT 0)");
|
||||
jdbcTemplate.execute(
|
||||
"CREATE TABLE IF NOT EXISTS sync_task ("
|
||||
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||
+ "name VARCHAR(128) NOT NULL, "
|
||||
+ "datasource_id BIGINT NOT NULL, "
|
||||
+ "query_sql TEXT NOT NULL, "
|
||||
+ "target_table VARCHAR(64) NOT NULL DEFAULT 'version_resource', "
|
||||
+ "batch_size INTEGER DEFAULT 200, "
|
||||
+ "retry_times INTEGER DEFAULT 1, "
|
||||
+ "cron_expr VARCHAR(64), "
|
||||
+ "schedule_enabled SMALLINT DEFAULT 0, "
|
||||
+ "sync_mode VARCHAR(16) DEFAULT 'FULL', "
|
||||
+ "increment_column VARCHAR(64), "
|
||||
+ "increment_value VARCHAR(128), "
|
||||
+ "unique_fields VARCHAR(256), "
|
||||
+ "enabled SMALLINT DEFAULT 1, "
|
||||
+ "last_schedule_time TIMESTAMP, "
|
||||
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
|
||||
+ "update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
|
||||
+ "deleted SMALLINT DEFAULT 0)");
|
||||
jdbcTemplate.execute(
|
||||
"CREATE TABLE IF NOT EXISTS sync_field_map ("
|
||||
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||
+ "task_id BIGINT NOT NULL, "
|
||||
+ "source_field VARCHAR(128) NOT NULL, "
|
||||
+ "target_field VARCHAR(64) NOT NULL, "
|
||||
+ "data_type VARCHAR(16) DEFAULT 'STRING', "
|
||||
+ "clean_rule VARCHAR(32) DEFAULT 'TRIM', "
|
||||
+ "required_flag SMALLINT DEFAULT 0, "
|
||||
+ "default_value VARCHAR(256), "
|
||||
+ "sort_no INTEGER DEFAULT 0)");
|
||||
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_sync_field_task ON sync_field_map (task_id)");
|
||||
jdbcTemplate.execute(
|
||||
"CREATE TABLE IF NOT EXISTS sync_log ("
|
||||
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||
+ "task_id BIGINT, "
|
||||
+ "datasource_id BIGINT, "
|
||||
+ "task_name VARCHAR(128), "
|
||||
+ "datasource_name VARCHAR(128), "
|
||||
+ "trigger_type VARCHAR(16), "
|
||||
+ "status VARCHAR(16), "
|
||||
+ "start_time TIMESTAMP, "
|
||||
+ "end_time TIMESTAMP, "
|
||||
+ "success_count INTEGER DEFAULT 0, "
|
||||
+ "fail_count INTEGER DEFAULT 0, "
|
||||
+ "skip_count INTEGER DEFAULT 0, "
|
||||
+ "error_message TEXT, "
|
||||
+ "detail TEXT, "
|
||||
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
|
||||
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_sync_log_task ON sync_log (task_id)");
|
||||
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_sync_log_start ON sync_log (start_time)");
|
||||
log.info("数据同步表已就绪");
|
||||
grantMenu();
|
||||
} catch (Exception e) {
|
||||
log.warn("自动创建数据同步表失败(不影响启动,请检查数据库权限):{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** 已有「数据采集」权限的角色补上「数据同步」,管理员本身不受角色栏目限制。 */
|
||||
private void grantMenu() {
|
||||
try {
|
||||
jdbcTemplate.execute(
|
||||
"INSERT INTO sys_role_menu (role_id, menu_code) "
|
||||
+ "SELECT DISTINCT role_id, 'sync' FROM sys_role_menu existing "
|
||||
+ "WHERE existing.menu_code = 'collect' "
|
||||
+ "AND NOT EXISTS (SELECT 1 FROM sys_role_menu s "
|
||||
+ "WHERE s.role_id = existing.role_id AND s.menu_code = 'sync')");
|
||||
} catch (Exception e) {
|
||||
log.warn("补充数据同步栏目权限失败:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.banben.modules.sync.controller;
|
||||
|
||||
import com.banben.common.PageResult;
|
||||
import com.banben.common.Result;
|
||||
import com.banben.modules.sync.dto.TargetColumnVO;
|
||||
import com.banben.modules.sync.entity.SyncDatasource;
|
||||
import com.banben.modules.sync.entity.SyncLog;
|
||||
import com.banben.modules.sync.entity.SyncTask;
|
||||
import com.banben.modules.sync.service.SyncService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 异构数据同步接口。连接、SQL 和字段映射都由调用方传入,服务端只负责保存和按配置执行。
|
||||
*/
|
||||
@Tag(name = "数据同步", description = "外部数据源配置、同步任务、手动同步与日志")
|
||||
@RestController
|
||||
@RequestMapping("/api/sync")
|
||||
@RequiredArgsConstructor
|
||||
public class SyncController {
|
||||
|
||||
private final SyncService syncService;
|
||||
|
||||
@Operation(summary = "数据源列表")
|
||||
@GetMapping("/datasource")
|
||||
public Result<List<SyncDatasource>> listDatasources() {
|
||||
return Result.success(syncService.listDatasources());
|
||||
}
|
||||
|
||||
@Operation(summary = "新增数据源")
|
||||
@PostMapping("/datasource")
|
||||
public Result<Long> createDatasource(@RequestBody SyncDatasource source) {
|
||||
source.setId(null);
|
||||
return Result.success(syncService.saveDatasource(source));
|
||||
}
|
||||
|
||||
@Operation(summary = "修改数据源")
|
||||
@PutMapping("/datasource/{id}")
|
||||
public Result<Void> updateDatasource(@PathVariable Long id, @RequestBody SyncDatasource source) {
|
||||
source.setId(id);
|
||||
syncService.saveDatasource(source);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "删除数据源")
|
||||
@DeleteMapping("/datasource/{id}")
|
||||
public Result<Void> removeDatasource(@PathVariable Long id) {
|
||||
syncService.removeDatasource(id);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "测试数据源连通性")
|
||||
@PostMapping("/datasource/test")
|
||||
public Result<String> testDatasource(@RequestBody SyncDatasource source) {
|
||||
syncService.testDatasource(source);
|
||||
return Result.success("连接成功");
|
||||
}
|
||||
|
||||
@Operation(summary = "按查询 SQL 读取外部列名,供配置映射")
|
||||
@PostMapping("/preview")
|
||||
public Result<List<String>> preview(@RequestBody PreviewRequest request) {
|
||||
return Result.success(syncService.previewColumns(request.getDatasource(), request.getQuerySql()));
|
||||
}
|
||||
|
||||
@Operation(summary = "可写入的业务表")
|
||||
@GetMapping("/target/tables")
|
||||
public Result<List<String>> targetTables() {
|
||||
return Result.success(syncService.listTargetTables());
|
||||
}
|
||||
|
||||
@Operation(summary = "目标表字段")
|
||||
@GetMapping("/target/columns")
|
||||
public Result<List<TargetColumnVO>> targetColumns(@RequestParam(defaultValue = "version_resource") String table) {
|
||||
return Result.success(syncService.listTargetColumns(table));
|
||||
}
|
||||
|
||||
@Operation(summary = "同步任务列表")
|
||||
@GetMapping("/task")
|
||||
public Result<List<SyncTask>> listTasks() {
|
||||
return Result.success(syncService.listTasks());
|
||||
}
|
||||
|
||||
@Operation(summary = "新增同步任务")
|
||||
@PostMapping("/task")
|
||||
public Result<Long> createTask(@RequestBody SyncTask task) {
|
||||
task.setId(null);
|
||||
return Result.success(syncService.saveTask(task));
|
||||
}
|
||||
|
||||
@Operation(summary = "修改同步任务")
|
||||
@PutMapping("/task/{id}")
|
||||
public Result<Void> updateTask(@PathVariable Long id, @RequestBody SyncTask task) {
|
||||
task.setId(id);
|
||||
syncService.saveTask(task);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "删除同步任务")
|
||||
@DeleteMapping("/task/{id}")
|
||||
public Result<Void> removeTask(@PathVariable Long id) {
|
||||
syncService.removeTask(id);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "手动触发同步")
|
||||
@PostMapping("/task/{id}/run")
|
||||
public Result<Long> run(@PathVariable Long id) {
|
||||
return Result.success(syncService.runTask(id, "MANUAL"));
|
||||
}
|
||||
|
||||
@Operation(summary = "同步日志")
|
||||
@GetMapping("/log")
|
||||
public Result<PageResult<SyncLog>> logs(@RequestParam(required = false) Long taskId,
|
||||
@RequestParam(defaultValue = "1") long current,
|
||||
@RequestParam(defaultValue = "10") long size) {
|
||||
return Result.success(syncService.pageLogs(taskId, current, size));
|
||||
}
|
||||
|
||||
@Operation(summary = "同步日志详情")
|
||||
@GetMapping("/log/{id}")
|
||||
public Result<SyncLog> log(@PathVariable Long id) {
|
||||
return Result.success(syncService.getLog(id));
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class PreviewRequest {
|
||||
private SyncDatasource datasource;
|
||||
private String querySql;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.banben.modules.sync.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 业务库目标表的一列,供页面做字段映射下拉。
|
||||
*/
|
||||
@Data
|
||||
public class TargetColumnVO {
|
||||
|
||||
private String name;
|
||||
|
||||
private String comment;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.banben.modules.sync.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 外部数据源连接。地址、账号、库类型都从本表读取,代码里不写死任何外部库。
|
||||
*/
|
||||
@Data
|
||||
@TableName("sync_datasource")
|
||||
@Schema(description = "同步数据源")
|
||||
public class SyncDatasource implements Serializable {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "数据源名称")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "数据库类型:MYSQL / ORACLE / SQLSERVER / POSTGRESQL / HIGHGO")
|
||||
private String dbType;
|
||||
|
||||
@Schema(description = "主机地址")
|
||||
private String host;
|
||||
|
||||
@Schema(description = "端口")
|
||||
private Integer port;
|
||||
|
||||
@Schema(description = "库名。Oracle 填服务名")
|
||||
private String dbName;
|
||||
|
||||
@Schema(description = "用户名")
|
||||
private String username;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
@Schema(description = "密码,只用于连接,接口不回传")
|
||||
private String password;
|
||||
|
||||
@Schema(description = "附加 JDBC 参数,空则用该类型的默认参数")
|
||||
private String jdbcParams;
|
||||
|
||||
@Schema(description = "1 启用 0 停用")
|
||||
private Integer enabled;
|
||||
|
||||
@Schema(description = "备注")
|
||||
private String remark;
|
||||
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.banben.modules.sync.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 一条字段映射:外部结果列 → 我方目标列,以及清洗、类型和是否必填。
|
||||
*/
|
||||
@Data
|
||||
@TableName("sync_field_map")
|
||||
@Schema(description = "同步字段映射")
|
||||
public class SyncFieldMap implements Serializable {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private Long taskId;
|
||||
|
||||
@Schema(description = "查询结果中的列名")
|
||||
private String sourceField;
|
||||
|
||||
@Schema(description = "目标表列名")
|
||||
private String targetField;
|
||||
|
||||
@Schema(description = "STRING / INTEGER / LONG / DECIMAL / DATE / DATETIME")
|
||||
private String dataType;
|
||||
|
||||
@Schema(description = "NONE / TRIM / UPPER / LOWER / DIGITS / COMPACT_DATE")
|
||||
private String cleanRule;
|
||||
|
||||
@Schema(description = "1 必填,空值记失败并不写入该行")
|
||||
private Integer requiredFlag;
|
||||
|
||||
@Schema(description = "源值为空时的默认值,支持 ${uuid} ${today} ${year} ${seq} ${task}")
|
||||
private String defaultValue;
|
||||
|
||||
private Integer sortNo;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.banben.modules.sync.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 一次同步的执行结果。失败原因写在 errorMessage,单行错误样例写在 detail。
|
||||
*/
|
||||
@Data
|
||||
@TableName("sync_log")
|
||||
@Schema(description = "同步日志")
|
||||
public class SyncLog implements Serializable {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private Long taskId;
|
||||
|
||||
private Long datasourceId;
|
||||
|
||||
private String taskName;
|
||||
|
||||
private String datasourceName;
|
||||
|
||||
@Schema(description = "MANUAL / SCHEDULE")
|
||||
private String triggerType;
|
||||
|
||||
@Schema(description = "RUNNING / SUCCESS / PARTIAL / FAILED")
|
||||
private String status;
|
||||
|
||||
private LocalDateTime startTime;
|
||||
|
||||
private LocalDateTime endTime;
|
||||
|
||||
private Integer successCount;
|
||||
|
||||
private Integer failCount;
|
||||
|
||||
private Integer skipCount;
|
||||
|
||||
private String errorMessage;
|
||||
|
||||
private String detail;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.banben.modules.sync.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 同步任务配置。查询语句和目标表都由现场填写。
|
||||
*/
|
||||
@Data
|
||||
@TableName("sync_task")
|
||||
@Schema(description = "同步任务")
|
||||
public class SyncTask implements Serializable {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "任务名称")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "数据源 ID")
|
||||
private Long datasourceId;
|
||||
|
||||
@Schema(description = "外部库查询 SQL,只允许单条 SELECT")
|
||||
private String querySql;
|
||||
|
||||
@Schema(description = "写入的业务表,默认 version_resource")
|
||||
private String targetTable;
|
||||
|
||||
@Schema(description = "每批写入条数")
|
||||
private Integer batchSize;
|
||||
|
||||
@Schema(description = "连接或查询失败时的重试次数")
|
||||
private Integer retryTimes;
|
||||
|
||||
@Schema(description = "定时表达式,6 位:秒 分 时 日 月 周")
|
||||
private String cronExpr;
|
||||
|
||||
@Schema(description = "1 启用定时 0 仅手动")
|
||||
private Integer scheduleEnabled;
|
||||
|
||||
@Schema(description = "FULL 全量 / INCREMENT 增量")
|
||||
private String syncMode;
|
||||
|
||||
@Schema(description = "增量水位列,预留")
|
||||
private String incrementColumn;
|
||||
|
||||
@Schema(description = "上次水位")
|
||||
private String incrementValue;
|
||||
|
||||
@Schema(description = "去重用的目标字段,逗号分隔")
|
||||
private String uniqueFields;
|
||||
|
||||
@Schema(description = "1 启用 0 停用")
|
||||
private Integer enabled;
|
||||
|
||||
@Schema(description = "上次定时触发时间")
|
||||
private LocalDateTime lastScheduleTime;
|
||||
|
||||
@TableField(exist = false)
|
||||
@Schema(description = "数据源名称,仅展示")
|
||||
private String datasourceName;
|
||||
|
||||
@TableField(exist = false)
|
||||
@Schema(description = "字段映射,保存任务时一并提交")
|
||||
private List<SyncFieldMap> mappings;
|
||||
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.banben.modules.sync.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.banben.modules.sync.entity.SyncDatasource;
|
||||
|
||||
public interface SyncDatasourceMapper extends BaseMapper<SyncDatasource> {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.banben.modules.sync.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.banben.modules.sync.entity.SyncFieldMap;
|
||||
|
||||
public interface SyncFieldMapMapper extends BaseMapper<SyncFieldMap> {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.banben.modules.sync.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.banben.modules.sync.entity.SyncLog;
|
||||
|
||||
public interface SyncLogMapper extends BaseMapper<SyncLog> {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.banben.modules.sync.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.banben.modules.sync.entity.SyncTask;
|
||||
|
||||
public interface SyncTaskMapper extends BaseMapper<SyncTask> {
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.banben.modules.sync.service;
|
||||
|
||||
import com.banben.common.PageResult;
|
||||
import com.banben.modules.sync.dto.TargetColumnVO;
|
||||
import com.banben.modules.sync.entity.SyncDatasource;
|
||||
import com.banben.modules.sync.entity.SyncLog;
|
||||
import com.banben.modules.sync.entity.SyncTask;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 异构数据同步:数据源、任务、手动执行和日志都从这里进出。
|
||||
*/
|
||||
public interface SyncService {
|
||||
|
||||
List<SyncDatasource> listDatasources();
|
||||
|
||||
Long saveDatasource(SyncDatasource source);
|
||||
|
||||
void removeDatasource(Long id);
|
||||
|
||||
void testDatasource(SyncDatasource source);
|
||||
|
||||
List<String> previewColumns(SyncDatasource source, String querySql);
|
||||
|
||||
List<String> listTargetTables();
|
||||
|
||||
List<TargetColumnVO> listTargetColumns(String table);
|
||||
|
||||
List<SyncTask> listTasks();
|
||||
|
||||
Long saveTask(SyncTask task);
|
||||
|
||||
void removeTask(Long id);
|
||||
|
||||
Long runTask(Long id, String triggerType);
|
||||
|
||||
PageResult<SyncLog> pageLogs(Long taskId, long current, long size);
|
||||
|
||||
SyncLog getLog(Long id);
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
package com.banben.modules.sync.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.banben.common.BusinessException;
|
||||
import com.banben.common.PageResult;
|
||||
import com.banben.modules.sync.dto.TargetColumnVO;
|
||||
import com.banben.modules.sync.entity.SyncDatasource;
|
||||
import com.banben.modules.sync.entity.SyncFieldMap;
|
||||
import com.banben.modules.sync.entity.SyncLog;
|
||||
import com.banben.modules.sync.entity.SyncTask;
|
||||
import com.banben.modules.sync.mapper.SyncDatasourceMapper;
|
||||
import com.banben.modules.sync.mapper.SyncFieldMapMapper;
|
||||
import com.banben.modules.sync.mapper.SyncLogMapper;
|
||||
import com.banben.modules.sync.mapper.SyncTaskMapper;
|
||||
import com.banben.modules.sync.service.SyncService;
|
||||
import com.banben.modules.sync.support.JdbcSources;
|
||||
import com.banben.modules.sync.support.SqlGuard;
|
||||
import com.banben.modules.sync.support.SyncRunner;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.scheduling.support.CronExpression;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 配置的增删改查。真正抽取数据由 {@link SyncRunner} 按库里的 SQL 和映射执行。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class SyncServiceImpl implements SyncService {
|
||||
|
||||
private static final Set<String> BLOCKED_TABLES = Set.of(
|
||||
"sync_datasource", "sync_task", "sync_field_map", "sync_log",
|
||||
"sys_user", "sys_role", "sys_role_menu"
|
||||
);
|
||||
|
||||
private final SyncDatasourceMapper datasourceMapper;
|
||||
private final SyncTaskMapper taskMapper;
|
||||
private final SyncFieldMapMapper fieldMapMapper;
|
||||
private final SyncLogMapper logMapper;
|
||||
private final SyncRunner syncRunner;
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
@Override
|
||||
public List<SyncDatasource> listDatasources() {
|
||||
return datasourceMapper.selectList(new LambdaQueryWrapper<SyncDatasource>()
|
||||
.orderByDesc(SyncDatasource::getCreateTime));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long saveDatasource(SyncDatasource source) {
|
||||
source.setDbType(JdbcSources.normalize(source.getDbType()));
|
||||
if (source.getName() == null || source.getName().isBlank()) {
|
||||
throw new BusinessException("请填写数据源名称");
|
||||
}
|
||||
if (source.getHost() == null || source.getHost().isBlank()) {
|
||||
throw new BusinessException("请填写数据库地址");
|
||||
}
|
||||
if (source.getPort() == null || source.getPort() < 1) {
|
||||
throw new BusinessException("请填写端口");
|
||||
}
|
||||
if (source.getDbName() == null || source.getDbName().isBlank()) {
|
||||
throw new BusinessException("请填写数据库名");
|
||||
}
|
||||
if (source.getUsername() == null || source.getUsername().isBlank()) {
|
||||
throw new BusinessException("请填写用户名");
|
||||
}
|
||||
if (source.getEnabled() == null) {
|
||||
source.setEnabled(1);
|
||||
}
|
||||
if (source.getId() == null) {
|
||||
if (source.getPassword() == null || source.getPassword().isBlank()) {
|
||||
throw new BusinessException("请填写密码");
|
||||
}
|
||||
datasourceMapper.insert(source);
|
||||
return source.getId();
|
||||
}
|
||||
SyncDatasource stored = requireDatasource(source.getId());
|
||||
if (source.getPassword() == null || source.getPassword().isBlank()) {
|
||||
source.setPassword(stored.getPassword());
|
||||
}
|
||||
datasourceMapper.updateById(source);
|
||||
return source.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeDatasource(Long id) {
|
||||
Long used = taskMapper.selectCount(new LambdaQueryWrapper<SyncTask>().eq(SyncTask::getDatasourceId, id));
|
||||
if (used != null && used > 0) {
|
||||
throw new BusinessException("该数据源下还有同步任务,请先删除任务");
|
||||
}
|
||||
datasourceMapper.deleteById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void testDatasource(SyncDatasource source) {
|
||||
fillPassword(source);
|
||||
saveDatasourceShape(source);
|
||||
try (Connection connection = JdbcSources.open(source)) {
|
||||
if (!connection.isValid(5)) {
|
||||
throw new BusinessException("连接未通过校验");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new BusinessException(JdbcSources.safeMessage(e, source.getPassword()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> previewColumns(SyncDatasource source, String querySql) {
|
||||
fillPassword(source);
|
||||
saveDatasourceShape(source);
|
||||
return syncRunner.previewColumns(source, querySql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> listTargetTables() {
|
||||
return jdbcTemplate.query(
|
||||
"SELECT table_name FROM information_schema.tables "
|
||||
+ "WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name",
|
||||
(rs, rowNum) -> rs.getString(1))
|
||||
.stream()
|
||||
.filter(name -> !BLOCKED_TABLES.contains(name.toLowerCase(Locale.ROOT)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TargetColumnVO> listTargetColumns(String table) {
|
||||
String name = SqlGuard.identifier(table, "目标表").toLowerCase(Locale.ROOT);
|
||||
if (BLOCKED_TABLES.contains(name)) {
|
||||
throw new BusinessException("不能选择系统配置表");
|
||||
}
|
||||
return jdbcTemplate.query(
|
||||
"SELECT a.attname AS name, col_description(a.attrelid, a.attnum) AS comment "
|
||||
+ "FROM pg_catalog.pg_attribute a "
|
||||
+ "JOIN pg_catalog.pg_class t ON a.attrelid = t.oid "
|
||||
+ "JOIN pg_catalog.pg_namespace n ON t.relnamespace = n.oid "
|
||||
+ "WHERE n.nspname = 'public' AND t.relname = ? "
|
||||
+ "AND a.attnum > 0 AND NOT a.attisdropped AND a.attname <> 'id' "
|
||||
+ "ORDER BY a.attnum",
|
||||
(rs, rowNum) -> {
|
||||
TargetColumnVO column = new TargetColumnVO();
|
||||
column.setName(rs.getString("name"));
|
||||
column.setComment(rs.getString("comment"));
|
||||
return column;
|
||||
},
|
||||
name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SyncTask> listTasks() {
|
||||
List<SyncTask> tasks = taskMapper.selectList(new LambdaQueryWrapper<SyncTask>()
|
||||
.orderByDesc(SyncTask::getCreateTime));
|
||||
for (SyncTask task : tasks) {
|
||||
SyncDatasource source = datasourceMapper.selectById(task.getDatasourceId());
|
||||
task.setDatasourceName(source == null ? "" : source.getName());
|
||||
task.setMappings(mappingsOf(task.getId()));
|
||||
}
|
||||
return tasks;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public Long saveTask(SyncTask task) {
|
||||
if (task.getName() == null || task.getName().isBlank()) {
|
||||
throw new BusinessException("请填写任务名称");
|
||||
}
|
||||
if (task.getDatasourceId() == null || datasourceMapper.selectById(task.getDatasourceId()) == null) {
|
||||
throw new BusinessException("请选择数据源");
|
||||
}
|
||||
task.setQuerySql(SqlGuard.selectSql(task.getQuerySql()));
|
||||
String table = SqlGuard.identifier(
|
||||
task.getTargetTable() == null || task.getTargetTable().isBlank() ? "version_resource" : task.getTargetTable(),
|
||||
"目标表").toLowerCase(Locale.ROOT);
|
||||
if (BLOCKED_TABLES.contains(table)) {
|
||||
throw new BusinessException("不能写入系统配置表");
|
||||
}
|
||||
if (listTargetColumns(table).isEmpty()) {
|
||||
throw new BusinessException("业务库中不存在表 " + table);
|
||||
}
|
||||
task.setTargetTable(table);
|
||||
if (task.getMappings() == null || task.getMappings().isEmpty()) {
|
||||
throw new BusinessException("请至少配置一条字段映射");
|
||||
}
|
||||
if (task.getBatchSize() == null || task.getBatchSize() < 1) {
|
||||
task.setBatchSize(200);
|
||||
}
|
||||
task.setBatchSize(Math.min(task.getBatchSize(), 2000));
|
||||
if (task.getRetryTimes() == null || task.getRetryTimes() < 0) {
|
||||
task.setRetryTimes(1);
|
||||
}
|
||||
task.setRetryTimes(Math.min(task.getRetryTimes(), 5));
|
||||
if (task.getScheduleEnabled() != null && task.getScheduleEnabled() == 1) {
|
||||
if (task.getCronExpr() == null || task.getCronExpr().isBlank()) {
|
||||
throw new BusinessException("启用定时时请填写 cron");
|
||||
}
|
||||
try {
|
||||
CronExpression.parse(task.getCronExpr().trim());
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new BusinessException("cron 不正确,格式为:秒 分 时 日 月 周");
|
||||
}
|
||||
task.setCronExpr(task.getCronExpr().trim());
|
||||
}
|
||||
if (task.getSyncMode() == null || task.getSyncMode().isBlank()) {
|
||||
task.setSyncMode("FULL");
|
||||
}
|
||||
task.setSyncMode(task.getSyncMode().trim().toUpperCase(Locale.ROOT));
|
||||
if (!"FULL".equals(task.getSyncMode()) && !"INCREMENT".equals(task.getSyncMode())) {
|
||||
throw new BusinessException("同步方式只能是全量或增量");
|
||||
}
|
||||
if ("INCREMENT".equals(task.getSyncMode()) && (task.getQuerySql() == null || !task.getQuerySql().contains("${watermark}"))) {
|
||||
throw new BusinessException("增量同步的 SQL 需要包含 ${watermark} 占位符");
|
||||
}
|
||||
if (task.getEnabled() == null) {
|
||||
task.setEnabled(1);
|
||||
}
|
||||
if (task.getScheduleEnabled() == null) {
|
||||
task.setScheduleEnabled(0);
|
||||
}
|
||||
if (task.getId() == null) {
|
||||
taskMapper.insert(task);
|
||||
} else {
|
||||
SyncTask stored = requireTask(task.getId());
|
||||
if (task.getIncrementValue() == null || task.getIncrementValue().isBlank()) {
|
||||
task.setIncrementValue(stored.getIncrementValue());
|
||||
}
|
||||
task.setLastScheduleTime(stored.getLastScheduleTime());
|
||||
taskMapper.updateById(task);
|
||||
fieldMapMapper.delete(new LambdaQueryWrapper<SyncFieldMap>().eq(SyncFieldMap::getTaskId, task.getId()));
|
||||
}
|
||||
int sort = 0;
|
||||
for (SyncFieldMap map : task.getMappings()) {
|
||||
if (map.getSourceField() == null || map.getSourceField().isBlank()
|
||||
|| map.getTargetField() == null || map.getTargetField().isBlank()) {
|
||||
throw new BusinessException("字段映射的源字段和目标字段都不能为空");
|
||||
}
|
||||
map.setId(null);
|
||||
map.setTaskId(task.getId());
|
||||
map.setSortNo(sort++);
|
||||
if (map.getDataType() == null || map.getDataType().isBlank()) {
|
||||
map.setDataType("STRING");
|
||||
}
|
||||
if (map.getCleanRule() == null || map.getCleanRule().isBlank()) {
|
||||
map.setCleanRule("TRIM");
|
||||
}
|
||||
if (map.getRequiredFlag() == null) {
|
||||
map.setRequiredFlag(0);
|
||||
}
|
||||
fieldMapMapper.insert(map);
|
||||
}
|
||||
return task.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTask(Long id) {
|
||||
if (syncRunner.isRunning(id)) {
|
||||
throw new BusinessException("任务正在同步,不能删除");
|
||||
}
|
||||
requireTask(id);
|
||||
taskMapper.deleteById(id);
|
||||
fieldMapMapper.delete(new LambdaQueryWrapper<SyncFieldMap>().eq(SyncFieldMap::getTaskId, id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long runTask(Long id, String triggerType) {
|
||||
SyncTask task = requireTask(id);
|
||||
if (task.getEnabled() != null && task.getEnabled() == 0) {
|
||||
throw new BusinessException("任务已停用");
|
||||
}
|
||||
if (syncRunner.isRunning(id)) {
|
||||
throw new BusinessException("该任务正在同步");
|
||||
}
|
||||
SyncDatasource source = requireDatasource(task.getDatasourceId());
|
||||
if (source.getEnabled() != null && source.getEnabled() == 0) {
|
||||
throw new BusinessException("数据源已停用");
|
||||
}
|
||||
List<SyncFieldMap> mappings = mappingsOf(id);
|
||||
if (mappings.isEmpty()) {
|
||||
throw new BusinessException("请先配置字段映射");
|
||||
}
|
||||
SyncLog syncLog = new SyncLog();
|
||||
syncLog.setTaskId(task.getId());
|
||||
syncLog.setDatasourceId(source.getId());
|
||||
syncLog.setTaskName(task.getName());
|
||||
syncLog.setDatasourceName(source.getName());
|
||||
syncLog.setTriggerType(triggerType);
|
||||
syncLog.setStatus("RUNNING");
|
||||
syncLog.setStartTime(LocalDateTime.now());
|
||||
syncLog.setSuccessCount(0);
|
||||
syncLog.setFailCount(0);
|
||||
syncLog.setSkipCount(0);
|
||||
syncLog.setCreateTime(LocalDateTime.now());
|
||||
logMapper.insert(syncLog);
|
||||
syncRunner.submit(task, source, mappings, syncLog);
|
||||
return syncLog.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResult<SyncLog> pageLogs(Long taskId, long current, long size) {
|
||||
LambdaQueryWrapper<SyncLog> wrapper = new LambdaQueryWrapper<SyncLog>().orderByDesc(SyncLog::getStartTime);
|
||||
if (taskId != null) {
|
||||
wrapper.eq(SyncLog::getTaskId, taskId);
|
||||
}
|
||||
Page<SyncLog> page = logMapper.selectPage(new Page<>(current, size), wrapper);
|
||||
return PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
|
||||
}
|
||||
|
||||
@Override
|
||||
public SyncLog getLog(Long id) {
|
||||
SyncLog log = logMapper.selectById(id);
|
||||
if (log == null) {
|
||||
throw new BusinessException("同步日志不存在");
|
||||
}
|
||||
return log;
|
||||
}
|
||||
|
||||
private void fillPassword(SyncDatasource source) {
|
||||
if (source.getPassword() != null && !source.getPassword().isBlank()) {
|
||||
return;
|
||||
}
|
||||
if (source.getId() == null) {
|
||||
throw new BusinessException("请填写密码");
|
||||
}
|
||||
SyncDatasource stored = requireDatasource(source.getId());
|
||||
source.setPassword(stored.getPassword());
|
||||
if (source.getHost() == null) {
|
||||
source.setHost(stored.getHost());
|
||||
}
|
||||
if (source.getDbType() == null) {
|
||||
source.setDbType(stored.getDbType());
|
||||
}
|
||||
if (source.getPort() == null) {
|
||||
source.setPort(stored.getPort());
|
||||
}
|
||||
if (source.getDbName() == null) {
|
||||
source.setDbName(stored.getDbName());
|
||||
}
|
||||
if (source.getUsername() == null) {
|
||||
source.setUsername(stored.getUsername());
|
||||
}
|
||||
if (source.getJdbcParams() == null) {
|
||||
source.setJdbcParams(stored.getJdbcParams());
|
||||
}
|
||||
}
|
||||
|
||||
/** 测试和预览只校验形态,不把未保存的连接写进库。 */
|
||||
private void saveDatasourceShape(SyncDatasource source) {
|
||||
JdbcSources.normalize(source.getDbType());
|
||||
if (source.getHost() == null || source.getHost().isBlank()
|
||||
|| source.getPort() == null || source.getDbName() == null || source.getDbName().isBlank()
|
||||
|| source.getUsername() == null || source.getUsername().isBlank()) {
|
||||
throw new BusinessException("请把地址、端口、库名和用户名填写完整");
|
||||
}
|
||||
}
|
||||
|
||||
private List<SyncFieldMap> mappingsOf(Long taskId) {
|
||||
return fieldMapMapper.selectList(new LambdaQueryWrapper<SyncFieldMap>()
|
||||
.eq(SyncFieldMap::getTaskId, taskId)
|
||||
.orderByAsc(SyncFieldMap::getSortNo)
|
||||
.orderByAsc(SyncFieldMap::getId));
|
||||
}
|
||||
|
||||
private SyncDatasource requireDatasource(Long id) {
|
||||
SyncDatasource source = datasourceMapper.selectById(id);
|
||||
if (source == null) {
|
||||
throw new BusinessException("数据源不存在");
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
private SyncTask requireTask(Long id) {
|
||||
SyncTask task = taskMapper.selectById(id);
|
||||
if (task == null) {
|
||||
throw new BusinessException("同步任务不存在");
|
||||
}
|
||||
return task;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.banben.modules.sync.support;
|
||||
|
||||
import com.banben.common.BusinessException;
|
||||
import com.banben.modules.sync.entity.SyncDatasource;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Locale;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* 按数据源配置拼出 JDBC 连接。类型决定驱动和 URL 形态,地址账号全部来自配置表。
|
||||
*/
|
||||
public final class JdbcSources {
|
||||
|
||||
private JdbcSources() {
|
||||
}
|
||||
|
||||
public static Connection open(SyncDatasource source) throws SQLException {
|
||||
String type = normalize(source.getDbType());
|
||||
loadDriver(type);
|
||||
Properties props = new Properties();
|
||||
props.setProperty("user", source.getUsername() == null ? "" : source.getUsername().trim());
|
||||
props.setProperty("password", source.getPassword() == null ? "" : source.getPassword());
|
||||
return DriverManager.getConnection(buildUrl(source, type), props);
|
||||
}
|
||||
|
||||
public static String normalize(String dbType) {
|
||||
if (dbType == null || dbType.isBlank()) {
|
||||
throw new BusinessException("请选择数据库类型");
|
||||
}
|
||||
return dbType.trim().toUpperCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
public static String safeMessage(SQLException exception, String password) {
|
||||
String message = exception.getMessage() == null ? "连接失败" : exception.getMessage();
|
||||
String lower = message.toLowerCase(Locale.ROOT);
|
||||
String text;
|
||||
if (lower.contains("access denied") || lower.contains("password authentication failed")
|
||||
|| lower.contains("login failed") || lower.contains("ora-01017")) {
|
||||
text = "用户名或密码错误";
|
||||
} else if (lower.contains("unknown database") || lower.contains("does not exist")
|
||||
|| lower.contains("ora-12514") || lower.contains("cannot open database")) {
|
||||
text = "数据库不存在或服务名不正确";
|
||||
} else if (lower.contains("connection refused") || lower.contains("communications link failure")
|
||||
|| lower.contains("connect timed out") || lower.contains("the network adapter")
|
||||
|| lower.contains("timeout")) {
|
||||
text = "连接被拒绝或超时,请确认现场网络和地址端口";
|
||||
} else {
|
||||
text = message;
|
||||
}
|
||||
if (password != null && !password.isBlank() && text.contains(password)) {
|
||||
text = text.replace(password, "******");
|
||||
}
|
||||
return clip(text, 500);
|
||||
}
|
||||
|
||||
static String buildUrl(SyncDatasource source, String type) {
|
||||
String host = required(source.getHost(), "数据库地址");
|
||||
int port = source.getPort() == null ? 0 : source.getPort();
|
||||
if (port <= 0 || port > 65535) {
|
||||
throw new BusinessException("端口不正确");
|
||||
}
|
||||
String db = required(source.getDbName(), "数据库名");
|
||||
String extra = source.getJdbcParams() == null ? "" : source.getJdbcParams().trim();
|
||||
return switch (type) {
|
||||
case "MYSQL" -> "jdbc:mysql://" + host + ":" + port + "/" + db + "?"
|
||||
+ (extra.isEmpty()
|
||||
? "useSSL=false&allowPublicKeyRetrieval=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&connectTimeout=8000"
|
||||
: extra);
|
||||
case "ORACLE" -> "jdbc:oracle:thin:@//" + host + ":" + port + "/" + db
|
||||
+ (extra.isEmpty() ? "" : "?" + extra);
|
||||
case "SQLSERVER" -> "jdbc:sqlserver://" + host + ":" + port
|
||||
+ ";databaseName=" + db
|
||||
+ ";encrypt=false;trustServerCertificate=true;loginTimeout=8"
|
||||
+ (extra.isEmpty() ? "" : ";" + extra.replace('&', ';'));
|
||||
case "POSTGRESQL", "HIGHGO" -> "jdbc:postgresql://" + host + ":" + port + "/" + db
|
||||
+ "?connectTimeout=8" + (extra.isEmpty() ? "" : "&" + extra);
|
||||
default -> throw new BusinessException("数据库类型只支持 MySQL、Oracle、SQL Server、PostgreSQL、瀚高");
|
||||
};
|
||||
}
|
||||
|
||||
private static void loadDriver(String type) {
|
||||
String className = switch (type) {
|
||||
case "MYSQL" -> "com.mysql.cj.jdbc.Driver";
|
||||
case "ORACLE" -> "oracle.jdbc.OracleDriver";
|
||||
case "SQLSERVER" -> "com.microsoft.sqlserver.jdbc.SQLServerDriver";
|
||||
case "POSTGRESQL", "HIGHGO" -> "org.postgresql.Driver";
|
||||
default -> throw new BusinessException("数据库类型只支持 MySQL、Oracle、SQL Server、PostgreSQL、瀚高");
|
||||
};
|
||||
try {
|
||||
Class.forName(className);
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new BusinessException("未加载 " + type + " 驱动:" + className);
|
||||
}
|
||||
}
|
||||
|
||||
private static String required(String value, String label) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new BusinessException("请填写" + label);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
public static String clip(String text, int max) {
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
String flat = text.replace('\r', ' ').replace('\n', ' ').trim();
|
||||
return flat.length() <= max ? flat : flat.substring(0, max);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.banben.modules.sync.support;
|
||||
|
||||
import com.banben.modules.sync.entity.SyncFieldMap;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Date;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 字段清洗、默认值和类型转换。规则来自字段映射配置,不针对某一家外部库写死。
|
||||
*/
|
||||
public final class RowConverter {
|
||||
|
||||
private static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
private RowConverter() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 可直接交给 JDBC 的值;转换失败时抛出 IllegalArgumentException
|
||||
*/
|
||||
public static Object convert(SyncFieldMap map, Object raw, long taskId, int sequence) {
|
||||
String text = raw == null ? "" : String.valueOf(raw).trim();
|
||||
text = clean(text, map.getCleanRule());
|
||||
if (text.isEmpty()) {
|
||||
text = applyDefault(map.getDefaultValue(), taskId, sequence);
|
||||
}
|
||||
if (text.isEmpty()) {
|
||||
if (map.getRequiredFlag() != null && map.getRequiredFlag() == 1) {
|
||||
throw new IllegalArgumentException("必填字段 " + label(map) + " 为空");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
String type = map.getDataType() == null ? "STRING" : map.getDataType().trim().toUpperCase(Locale.ROOT);
|
||||
try {
|
||||
return switch (type) {
|
||||
case "INTEGER" -> Integer.valueOf(text);
|
||||
case "LONG" -> Long.valueOf(text);
|
||||
case "DECIMAL" -> new BigDecimal(text);
|
||||
case "DATE" -> Date.valueOf(parseDate(text));
|
||||
case "DATETIME" -> Timestamp.valueOf(parseDateTime(text));
|
||||
default -> text;
|
||||
};
|
||||
} catch (RuntimeException e) {
|
||||
throw new IllegalArgumentException("字段 " + label(map) + " 无法转成 " + type + ":" + text);
|
||||
}
|
||||
}
|
||||
|
||||
private static String label(SyncFieldMap map) {
|
||||
return map.getTargetField() + "(" + map.getSourceField() + ")";
|
||||
}
|
||||
|
||||
static String clean(String text, String rule) {
|
||||
if (text == null || text.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
String name = rule == null ? "TRIM" : rule.trim().toUpperCase(Locale.ROOT);
|
||||
return switch (name) {
|
||||
case "NONE" -> text;
|
||||
case "UPPER" -> text.toUpperCase(Locale.ROOT);
|
||||
case "LOWER" -> text.toLowerCase(Locale.ROOT);
|
||||
case "DIGITS" -> text.replaceAll("\\D", "");
|
||||
case "COMPACT_DATE" -> compactDate(text);
|
||||
default -> text.trim();
|
||||
};
|
||||
}
|
||||
|
||||
private static String applyDefault(String template, long taskId, int sequence) {
|
||||
if (template == null || template.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
LocalDate today = LocalDate.now();
|
||||
return template
|
||||
.replace("${uuid}", UUID.randomUUID().toString().replace("-", ""))
|
||||
.replace("${today}", today.format(DAY))
|
||||
.replace("${year}", String.valueOf(today.getYear()))
|
||||
.replace("${seq}", String.valueOf(sequence))
|
||||
.replace("${task}", String.valueOf(taskId))
|
||||
.trim();
|
||||
}
|
||||
|
||||
private static String compactDate(String text) {
|
||||
String digits = text.replaceAll("\\D", "");
|
||||
if (digits.length() >= 8) {
|
||||
return digits.substring(0, 8);
|
||||
}
|
||||
if (digits.length() == 6) {
|
||||
return digits + "01";
|
||||
}
|
||||
if (digits.length() == 4) {
|
||||
return digits + "0101";
|
||||
}
|
||||
return digits;
|
||||
}
|
||||
|
||||
private static LocalDate parseDate(String text) {
|
||||
String digits = text.replaceAll("\\D", "");
|
||||
if (digits.length() >= 8) {
|
||||
return LocalDate.parse(digits.substring(0, 8), DAY);
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(text);
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new IllegalArgumentException(text);
|
||||
}
|
||||
}
|
||||
|
||||
private static LocalDateTime parseDateTime(String text) {
|
||||
String normalized = text.replace('T', ' ').replace('/', '-');
|
||||
try {
|
||||
if (normalized.length() == 10) {
|
||||
return LocalDate.parse(normalized).atStartOfDay();
|
||||
}
|
||||
return LocalDateTime.parse(normalized, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||
} catch (DateTimeParseException e) {
|
||||
return parseDate(text).atStartOfDay();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.banben.modules.sync.support;
|
||||
|
||||
import com.banben.common.BusinessException;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 查询语句和目标表名的约束。SQL 由配置提供,这里只挡住多语句和明显的写操作。
|
||||
*/
|
||||
public final class SqlGuard {
|
||||
|
||||
private static final Pattern IDENT = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*");
|
||||
|
||||
private SqlGuard() {
|
||||
}
|
||||
|
||||
public static String selectSql(String sql) {
|
||||
if (sql == null || sql.isBlank()) {
|
||||
throw new BusinessException("请填写查询 SQL");
|
||||
}
|
||||
String text = sql.trim();
|
||||
if (text.endsWith(";")) {
|
||||
text = text.substring(0, text.length() - 1).trim();
|
||||
}
|
||||
if (text.indexOf(';') >= 0) {
|
||||
throw new BusinessException("查询 SQL 只能有一条语句");
|
||||
}
|
||||
String head = text.toLowerCase(Locale.ROOT);
|
||||
if (!head.startsWith("select") && !head.startsWith("with")) {
|
||||
throw new BusinessException("查询 SQL 只能是 SELECT");
|
||||
}
|
||||
if (text.length() > 20000) {
|
||||
throw new BusinessException("查询 SQL 过长");
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
public static String identifier(String name, String label) {
|
||||
if (name == null || !IDENT.matcher(name.trim()).matches()) {
|
||||
throw new BusinessException(label + "只能使用字母、数字和下划线");
|
||||
}
|
||||
return name.trim();
|
||||
}
|
||||
|
||||
public static String quote(String identifier) {
|
||||
return "\"" + identifier(identifier, "字段名") + "\"";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
package com.banben.modules.sync.support;
|
||||
|
||||
import com.banben.common.BusinessException;
|
||||
import com.banben.modules.sync.entity.SyncDatasource;
|
||||
import com.banben.modules.sync.entity.SyncFieldMap;
|
||||
import com.banben.modules.sync.entity.SyncLog;
|
||||
import com.banben.modules.sync.entity.SyncTask;
|
||||
import com.banben.modules.sync.mapper.SyncLogMapper;
|
||||
import com.banben.modules.sync.mapper.SyncTaskMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* 按任务配置抽取、转换、校验、去重并写入业务库。
|
||||
* 连接失败会按任务上的重试次数重试;已经写入过数据后不再整批重跑,避免重复插入。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class SyncRunner {
|
||||
|
||||
private static final Set<String> BLOCKED_TABLES = Set.of(
|
||||
"sync_datasource", "sync_task", "sync_field_map", "sync_log",
|
||||
"sys_user", "sys_role", "sys_role_menu"
|
||||
);
|
||||
|
||||
private static final List<String> SYSTEM_COLUMNS = List.of(
|
||||
"govern_status", "deleted", "create_time", "update_time",
|
||||
"abnormal_flag", "sensitive_flag", "is_special", "manage_status"
|
||||
);
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final SyncLogMapper logMapper;
|
||||
private final SyncTaskMapper taskMapper;
|
||||
private final ExecutorService workers = Executors.newFixedThreadPool(2, runnable -> {
|
||||
Thread thread = new Thread(runnable, "sync-worker");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
private final Set<Long> running = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public void submit(SyncTask task, SyncDatasource source, List<SyncFieldMap> mappings, SyncLog syncLog) {
|
||||
if (!running.add(task.getId())) {
|
||||
syncLog.setStatus("FAILED");
|
||||
syncLog.setEndTime(LocalDateTime.now());
|
||||
syncLog.setErrorMessage("该任务正在同步");
|
||||
logMapper.updateById(syncLog);
|
||||
return;
|
||||
}
|
||||
workers.submit(() -> {
|
||||
try {
|
||||
execute(task, source, mappings, syncLog);
|
||||
} catch (Exception e) {
|
||||
log.error("同步任务 {} 执行失败", task.getId(), e);
|
||||
finish(syncLog, task, 0, 0, 0, null, e.getMessage(), null);
|
||||
} finally {
|
||||
running.remove(task.getId());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public boolean isRunning(Long taskId) {
|
||||
return running.contains(taskId);
|
||||
}
|
||||
|
||||
public List<String> previewColumns(SyncDatasource source, String sql) {
|
||||
String query = applyWatermark(SqlGuard.selectSql(sql), null, "FULL");
|
||||
try (Connection connection = JdbcSources.open(source);
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.setMaxRows(1);
|
||||
statement.setQueryTimeout(20);
|
||||
try (ResultSet rs = statement.executeQuery(query)) {
|
||||
ResultSetMetaData meta = rs.getMetaData();
|
||||
List<String> columns = new ArrayList<>();
|
||||
for (int i = 1; i <= meta.getColumnCount(); i++) {
|
||||
columns.add(meta.getColumnLabel(i));
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new BusinessException(JdbcSources.safeMessage(e, source.getPassword()));
|
||||
}
|
||||
}
|
||||
|
||||
private void execute(SyncTask task, SyncDatasource source, List<SyncFieldMap> mappings, SyncLog syncLog) {
|
||||
String table = SqlGuard.identifier(task.getTargetTable(), "目标表");
|
||||
if (BLOCKED_TABLES.contains(table.toLowerCase(Locale.ROOT))) {
|
||||
finish(syncLog, task, 0, 0, 0, null, "不能写入系统配置表 " + table, null);
|
||||
return;
|
||||
}
|
||||
Set<String> targetColumns = loadColumns(table);
|
||||
if (targetColumns.isEmpty()) {
|
||||
finish(syncLog, task, 0, 0, 0, null, "业务库中不存在表 " + table, null);
|
||||
return;
|
||||
}
|
||||
List<String> uniqueFields = uniqueFields(task, targetColumns);
|
||||
String sql = applyWatermark(SqlGuard.selectSql(task.getQuerySql()), task.getIncrementValue(), task.getSyncMode());
|
||||
int batchSize = task.getBatchSize() == null || task.getBatchSize() < 1 ? 200 : Math.min(task.getBatchSize(), 2000);
|
||||
int retries = task.getRetryTimes() == null || task.getRetryTimes() < 0 ? 0 : Math.min(task.getRetryTimes(), 5);
|
||||
|
||||
Extracted extracted = new Extracted();
|
||||
extracted.watermark = task.getIncrementValue();
|
||||
StringBuilder detail = new StringBuilder();
|
||||
int attempt = 0;
|
||||
while (true) {
|
||||
try {
|
||||
readAndWrite(task, source, mappings, table, targetColumns, uniqueFields, sql, batchSize, detail, extracted);
|
||||
break;
|
||||
} catch (SQLException e) {
|
||||
attempt++;
|
||||
String message = JdbcSources.safeMessage(e, source.getPassword());
|
||||
log.warn("同步任务 {} 第 {} 次失败:{}", task.getId(), attempt, message);
|
||||
if (extracted.success > 0 || attempt > retries) {
|
||||
finish(syncLog, task, extracted.success, extracted.failed, extracted.skipped,
|
||||
extracted.watermark, message, detail.toString());
|
||||
return;
|
||||
}
|
||||
sleep(attempt);
|
||||
}
|
||||
}
|
||||
finish(syncLog, task, extracted.success, extracted.failed, extracted.skipped,
|
||||
extracted.watermark, null, detail.toString());
|
||||
}
|
||||
|
||||
private void readAndWrite(SyncTask task, SyncDatasource source, List<SyncFieldMap> mappings,
|
||||
String table, Set<String> targetColumns, List<String> uniqueFields,
|
||||
String sql, int batchSize, StringBuilder detail, Extracted extracted) throws SQLException {
|
||||
InsertPlan plan = insertPlan(task.getId(), table, mappings, targetColumns);
|
||||
List<Map<String, Object>> batch = new ArrayList<>();
|
||||
int sequence = 0;
|
||||
try (Connection connection = JdbcSources.open(source);
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.setFetchSize(batchSize);
|
||||
statement.setQueryTimeout(300);
|
||||
try (ResultSet rs = statement.executeQuery(sql)) {
|
||||
Map<String, Integer> labels = columnIndex(rs.getMetaData());
|
||||
while (rs.next()) {
|
||||
sequence++;
|
||||
try {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
for (SyncFieldMap map : mappings) {
|
||||
Object raw = readRaw(rs, labels, map.getSourceField());
|
||||
row.put(map.getTargetField().toLowerCase(Locale.ROOT),
|
||||
RowConverter.convert(map, raw, task.getId(), sequence));
|
||||
}
|
||||
fillSystem(row, targetColumns);
|
||||
String nextWatermark = readWatermark(rs, labels, task.getIncrementColumn());
|
||||
if (nextWatermark != null) {
|
||||
extracted.watermark = maxWatermark(extracted.watermark, nextWatermark);
|
||||
}
|
||||
batch.add(row);
|
||||
} catch (IllegalArgumentException e) {
|
||||
extracted.failed++;
|
||||
appendDetail(detail, sequence, e.getMessage());
|
||||
}
|
||||
if (batch.size() >= batchSize) {
|
||||
writeBatch(plan, uniqueFields, batch, extracted, detail);
|
||||
batch.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!batch.isEmpty()) {
|
||||
writeBatch(plan, uniqueFields, batch, extracted, detail);
|
||||
}
|
||||
}
|
||||
|
||||
private void writeBatch(InsertPlan plan, List<String> uniqueFields, List<Map<String, Object>> batch,
|
||||
Extracted extracted, StringBuilder detail) {
|
||||
List<Map<String, Object>> fresh = dropDuplicates(plan.table, uniqueFields, batch, extracted);
|
||||
if (fresh.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<Object[]> args = new ArrayList<>();
|
||||
for (Map<String, Object> row : fresh) {
|
||||
Object[] values = new Object[plan.columns.size()];
|
||||
for (int i = 0; i < plan.columns.size(); i++) {
|
||||
values[i] = row.get(plan.columns.get(i));
|
||||
}
|
||||
args.add(values);
|
||||
}
|
||||
try {
|
||||
jdbcTemplate.batchUpdate(plan.sql, args);
|
||||
extracted.success += args.size();
|
||||
} catch (DataAccessException batchError) {
|
||||
for (int i = 0; i < args.size(); i++) {
|
||||
try {
|
||||
jdbcTemplate.update(plan.sql, args.get(i));
|
||||
extracted.success++;
|
||||
} catch (DataAccessException rowError) {
|
||||
extracted.failed++;
|
||||
appendDetail(detail, 0, JdbcSources.clip(rowError.getMostSpecificCause().getMessage(), 180));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> dropDuplicates(String table, List<String> uniqueFields,
|
||||
List<Map<String, Object>> batch, Extracted extracted) {
|
||||
if (uniqueFields.isEmpty()) {
|
||||
return batch;
|
||||
}
|
||||
Set<String> seen = new LinkedHashSet<>();
|
||||
List<Map<String, Object>> distinct = new ArrayList<>();
|
||||
for (Map<String, Object> row : batch) {
|
||||
String key = keyOf(row, uniqueFields);
|
||||
if (key == null || !seen.add(key)) {
|
||||
extracted.skipped++;
|
||||
continue;
|
||||
}
|
||||
distinct.add(row);
|
||||
}
|
||||
if (distinct.isEmpty()) {
|
||||
return distinct;
|
||||
}
|
||||
Set<String> existing = loadExisting(table, uniqueFields, distinct);
|
||||
List<Map<String, Object>> fresh = new ArrayList<>();
|
||||
for (Map<String, Object> row : distinct) {
|
||||
if (existing.contains(keyOf(row, uniqueFields))) {
|
||||
extracted.skipped++;
|
||||
} else {
|
||||
fresh.add(row);
|
||||
}
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
|
||||
private Set<String> loadExisting(String table, List<String> uniqueFields, List<Map<String, Object>> rows) {
|
||||
StringBuilder sql = new StringBuilder("SELECT ");
|
||||
for (int i = 0; i < uniqueFields.size(); i++) {
|
||||
if (i > 0) {
|
||||
sql.append(", ");
|
||||
}
|
||||
sql.append(SqlGuard.quote(uniqueFields.get(i)));
|
||||
}
|
||||
sql.append(" FROM ").append(SqlGuard.quote(table)).append(" WHERE (");
|
||||
for (int i = 0; i < uniqueFields.size(); i++) {
|
||||
if (i > 0) {
|
||||
sql.append(", ");
|
||||
}
|
||||
sql.append(SqlGuard.quote(uniqueFields.get(i)));
|
||||
}
|
||||
sql.append(") IN (");
|
||||
List<Object> args = new ArrayList<>();
|
||||
for (int r = 0; r < rows.size(); r++) {
|
||||
if (r > 0) {
|
||||
sql.append(", ");
|
||||
}
|
||||
sql.append("(");
|
||||
for (int c = 0; c < uniqueFields.size(); c++) {
|
||||
if (c > 0) {
|
||||
sql.append(", ");
|
||||
}
|
||||
sql.append("?");
|
||||
args.add(rows.get(r).get(uniqueFields.get(c)));
|
||||
}
|
||||
sql.append(")");
|
||||
}
|
||||
sql.append(")");
|
||||
if (columnExists(table, "deleted")) {
|
||||
sql.append(" AND deleted = 0");
|
||||
}
|
||||
Set<String> found = new LinkedHashSet<>();
|
||||
jdbcTemplate.query(sql.toString(), rs -> {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
for (String field : uniqueFields) {
|
||||
row.put(field, rs.getObject(field));
|
||||
}
|
||||
found.add(keyOf(row, uniqueFields));
|
||||
}, args.toArray());
|
||||
return found;
|
||||
}
|
||||
|
||||
private InsertPlan insertPlan(long taskId, String table, List<SyncFieldMap> mappings, Set<String> targetColumns) {
|
||||
List<String> columns = new ArrayList<>();
|
||||
for (SyncFieldMap map : mappings) {
|
||||
String field = SqlGuard.identifier(map.getTargetField(), "目标字段").toLowerCase(Locale.ROOT);
|
||||
if (!targetColumns.contains(field)) {
|
||||
throw new BusinessException("目标表 " + table + " 没有字段 " + field);
|
||||
}
|
||||
if (!columns.contains(field)) {
|
||||
columns.add(field);
|
||||
}
|
||||
}
|
||||
InsertPlan plan = new InsertPlan();
|
||||
plan.table = table;
|
||||
plan.columns = new ArrayList<>(columns);
|
||||
for (String system : SYSTEM_COLUMNS) {
|
||||
if (targetColumns.contains(system) && !plan.columns.contains(system)) {
|
||||
plan.columns.add(system);
|
||||
}
|
||||
}
|
||||
StringBuilder sql = new StringBuilder("INSERT INTO ").append(SqlGuard.quote(table)).append(" (");
|
||||
StringBuilder holders = new StringBuilder();
|
||||
for (int i = 0; i < plan.columns.size(); i++) {
|
||||
if (i > 0) {
|
||||
sql.append(", ");
|
||||
holders.append(", ");
|
||||
}
|
||||
sql.append(SqlGuard.quote(plan.columns.get(i)));
|
||||
holders.append("?");
|
||||
}
|
||||
sql.append(") VALUES (").append(holders).append(")");
|
||||
plan.sql = sql.toString();
|
||||
log.debug("任务 {} 写入语句 {}", taskId, plan.sql);
|
||||
return plan;
|
||||
}
|
||||
|
||||
private void fillSystem(Map<String, Object> row, Set<String> targetColumns) {
|
||||
Timestamp now = Timestamp.valueOf(LocalDateTime.now());
|
||||
putIfAbsent(row, targetColumns, "govern_status", "RAW");
|
||||
putIfAbsent(row, targetColumns, "deleted", 0);
|
||||
putIfAbsent(row, targetColumns, "abnormal_flag", 0);
|
||||
putIfAbsent(row, targetColumns, "sensitive_flag", 0);
|
||||
putIfAbsent(row, targetColumns, "is_special", 0);
|
||||
putIfAbsent(row, targetColumns, "manage_status", 0);
|
||||
putIfAbsent(row, targetColumns, "create_time", now);
|
||||
putIfAbsent(row, targetColumns, "update_time", now);
|
||||
}
|
||||
|
||||
private void putIfAbsent(Map<String, Object> row, Set<String> columns, String name, Object value) {
|
||||
if (columns.contains(name) && !row.containsKey(name)) {
|
||||
row.put(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> loadColumns(String table) {
|
||||
List<String> names = jdbcTemplate.query(
|
||||
"SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = ?",
|
||||
(rs, rowNum) -> rs.getString(1).toLowerCase(Locale.ROOT),
|
||||
table.toLowerCase(Locale.ROOT));
|
||||
return new LinkedHashSet<>(names);
|
||||
}
|
||||
|
||||
private boolean columnExists(String table, String column) {
|
||||
Integer count = jdbcTemplate.queryForObject(
|
||||
"SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = 'public' AND table_name = ? AND column_name = ?",
|
||||
Integer.class, table.toLowerCase(Locale.ROOT), column.toLowerCase(Locale.ROOT));
|
||||
return count != null && count > 0;
|
||||
}
|
||||
|
||||
private List<String> uniqueFields(SyncTask task, Set<String> targetColumns) {
|
||||
if (task.getUniqueFields() == null || task.getUniqueFields().isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> fields = new ArrayList<>();
|
||||
for (String part : task.getUniqueFields().split(",")) {
|
||||
if (part.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String field = SqlGuard.identifier(part, "去重字段").toLowerCase(Locale.ROOT);
|
||||
if (!targetColumns.contains(field)) {
|
||||
throw new BusinessException("去重字段不在目标表中:" + field);
|
||||
}
|
||||
fields.add(field);
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
private Map<String, Integer> columnIndex(ResultSetMetaData meta) throws SQLException {
|
||||
Map<String, Integer> labels = new LinkedHashMap<>();
|
||||
for (int i = 1; i <= meta.getColumnCount(); i++) {
|
||||
labels.put(meta.getColumnLabel(i).toLowerCase(Locale.ROOT), i);
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
private Object readRaw(ResultSet rs, Map<String, Integer> labels, String sourceField) throws SQLException {
|
||||
Integer index = labels.get(sourceField.toLowerCase(Locale.ROOT));
|
||||
if (index == null) {
|
||||
throw new IllegalArgumentException("查询结果没有列 " + sourceField);
|
||||
}
|
||||
return rs.getObject(index);
|
||||
}
|
||||
|
||||
private String readWatermark(ResultSet rs, Map<String, Integer> labels, String column) throws SQLException {
|
||||
if (column == null || column.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
Integer index = labels.get(column.trim().toLowerCase(Locale.ROOT));
|
||||
if (index == null) {
|
||||
return null;
|
||||
}
|
||||
Object value = rs.getObject(index);
|
||||
return value == null ? null : String.valueOf(value).trim();
|
||||
}
|
||||
|
||||
static String applyWatermark(String sql, String watermark, String mode) {
|
||||
if (!sql.contains("${watermark}")) {
|
||||
return sql;
|
||||
}
|
||||
String value = "INCREMENT".equalsIgnoreCase(mode) && watermark != null ? watermark : "";
|
||||
return sql.replace("${watermark}", "'" + value.replace("'", "''") + "'");
|
||||
}
|
||||
|
||||
static String maxWatermark(String current, String next) {
|
||||
if (next == null || next.isBlank()) {
|
||||
return current;
|
||||
}
|
||||
if (current == null || current.isBlank()) {
|
||||
return next;
|
||||
}
|
||||
if (current.chars().allMatch(Character::isDigit) && next.chars().allMatch(Character::isDigit)) {
|
||||
return new BigDecimal(next).compareTo(new BigDecimal(current)) > 0 ? next : current;
|
||||
}
|
||||
return next.compareTo(current) > 0 ? next : current;
|
||||
}
|
||||
|
||||
private String keyOf(Map<String, Object> row, List<String> fields) {
|
||||
StringBuilder key = new StringBuilder();
|
||||
for (String field : fields) {
|
||||
Object value = row.get(field);
|
||||
if (value == null || String.valueOf(value).isBlank()) {
|
||||
return null;
|
||||
}
|
||||
key.append('\u0001').append(value);
|
||||
}
|
||||
return key.toString();
|
||||
}
|
||||
|
||||
private void finish(SyncLog syncLog, SyncTask task, int success, int failed, int skipped,
|
||||
String watermark, String error, String detail) {
|
||||
syncLog.setSuccessCount(success);
|
||||
syncLog.setFailCount(failed);
|
||||
syncLog.setSkipCount(skipped);
|
||||
syncLog.setEndTime(LocalDateTime.now());
|
||||
syncLog.setErrorMessage(JdbcSources.clip(error, 2000));
|
||||
syncLog.setDetail(JdbcSources.clip(detail, 4000));
|
||||
if (error != null && success == 0) {
|
||||
syncLog.setStatus("FAILED");
|
||||
} else if (failed > 0 || error != null) {
|
||||
syncLog.setStatus("PARTIAL");
|
||||
} else {
|
||||
syncLog.setStatus("SUCCESS");
|
||||
}
|
||||
logMapper.updateById(syncLog);
|
||||
if (error == null && watermark != null && !watermark.equals(task.getIncrementValue())) {
|
||||
task.setIncrementValue(watermark);
|
||||
taskMapper.updateById(task);
|
||||
}
|
||||
}
|
||||
|
||||
private void appendDetail(StringBuilder detail, int sequence, String message) {
|
||||
if (detail.length() > 3500) {
|
||||
return;
|
||||
}
|
||||
if (sequence > 0) {
|
||||
detail.append("第").append(sequence).append("行:");
|
||||
}
|
||||
detail.append(message).append('\n');
|
||||
}
|
||||
|
||||
private void sleep(int attempt) {
|
||||
try {
|
||||
Thread.sleep(1000L * attempt);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Extracted {
|
||||
private int success;
|
||||
private int failed;
|
||||
private int skipped;
|
||||
private String watermark;
|
||||
}
|
||||
|
||||
private static final class InsertPlan {
|
||||
private String table;
|
||||
private String sql;
|
||||
private List<String> columns;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.banben.modules.synchub;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.banben.modules.synchub.entity.SyncHubRecord;
|
||||
import com.banben.modules.synchub.mapper.SyncHubRecordMapper;
|
||||
import com.banben.modules.synchub.service.SyncHubService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 把还没超过次数的失败记录再送一次。调度开关沿用现有的定时任务配置。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class SyncHubRetryScheduler {
|
||||
|
||||
private final SyncHubRecordMapper recordMapper;
|
||||
private final SyncHubService syncHubService;
|
||||
|
||||
@Scheduled(fixedDelay = 60000, initialDelay = 45000)
|
||||
public void retryFailed() {
|
||||
List<SyncHubRecord> failed = recordMapper.selectList(new LambdaQueryWrapper<SyncHubRecord>()
|
||||
.eq(SyncHubRecord::getStatus, "FAILED")
|
||||
.apply("retry_count < max_retry")
|
||||
.orderByAsc(SyncHubRecord::getId)
|
||||
.last("LIMIT 5"));
|
||||
for (SyncHubRecord record : failed) {
|
||||
syncHubService.retryQuiet(record.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.banben.modules.synchub;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.banben.modules.synchub.model.BookDocument;
|
||||
import com.banben.modules.synchub.service.BookCleaner;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 启动时补齐汇聚用的两张表。已有数据不动,也不改 version_resource。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class SyncHubTableInitializer {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final BookCleaner cleaner;
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void init() {
|
||||
jdbcTemplate.execute(
|
||||
"CREATE TABLE IF NOT EXISTS sync_hub_record ("
|
||||
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||
+ "task_no VARCHAR(64) NOT NULL, "
|
||||
+ "direction VARCHAR(8) NOT NULL, "
|
||||
+ "source_node VARCHAR(32), "
|
||||
+ "target_node VARCHAR(32), "
|
||||
+ "source_db VARCHAR(32), "
|
||||
+ "book_count INTEGER DEFAULT 0, "
|
||||
+ "skip_count INTEGER DEFAULT 0, "
|
||||
+ "status VARCHAR(16) NOT NULL, "
|
||||
+ "error_message VARCHAR(1000), "
|
||||
+ "retry_count INTEGER DEFAULT 0, "
|
||||
+ "max_retry INTEGER DEFAULT 3, "
|
||||
+ "start_time TIMESTAMP, "
|
||||
+ "end_time TIMESTAMP, "
|
||||
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
|
||||
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_sync_hub_record_status ON sync_hub_record (status, create_time)");
|
||||
jdbcTemplate.execute(
|
||||
"CREATE TABLE IF NOT EXISTS sync_hub_book ("
|
||||
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||
+ "holder VARCHAR(32) NOT NULL, "
|
||||
+ "doc_id VARCHAR(320) NOT NULL, "
|
||||
+ "match_key VARCHAR(320), "
|
||||
+ "node_code VARCHAR(32), "
|
||||
+ "source_db VARCHAR(32), "
|
||||
+ "process_no VARCHAR(128), "
|
||||
+ "title VARCHAR(512), "
|
||||
+ "media_type VARCHAR(32), "
|
||||
+ "payload TEXT NOT NULL, "
|
||||
+ "update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
|
||||
jdbcTemplate.execute("CREATE UNIQUE INDEX IF NOT EXISTS uk_sync_hub_book ON sync_hub_book (holder, doc_id)");
|
||||
jdbcTemplate.execute("ALTER TABLE sync_hub_record ADD COLUMN IF NOT EXISTS skip_count INTEGER DEFAULT 0");
|
||||
jdbcTemplate.execute("ALTER TABLE sync_hub_book ADD COLUMN IF NOT EXISTS match_key VARCHAR(320)");
|
||||
jdbcTemplate.execute("ALTER TABLE sync_hub_book ALTER COLUMN doc_id TYPE VARCHAR(320)");
|
||||
backfillMatchKeys();
|
||||
jdbcTemplate.execute("CREATE UNIQUE INDEX IF NOT EXISTS uk_sync_hub_book_match ON sync_hub_book (holder, match_key)");
|
||||
log.info("图书汇聚表已就绪");
|
||||
}
|
||||
|
||||
/** 给早先写入的书补上比对键。同一本书只留最早的一条。 */
|
||||
private void backfillMatchKeys() {
|
||||
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
|
||||
"SELECT id, holder, payload FROM sync_hub_book WHERE match_key IS NULL OR match_key = '' ORDER BY id");
|
||||
for (Map<String, Object> row : rows) {
|
||||
long id = ((Number) row.get("id")).longValue();
|
||||
String holder = String.valueOf(row.get("holder"));
|
||||
BookDocument book;
|
||||
try {
|
||||
book = objectMapper.readValue(String.valueOf(row.get("payload")), BookDocument.class);
|
||||
} catch (Exception e) {
|
||||
continue;
|
||||
}
|
||||
String key = cleaner.matchKey(book);
|
||||
List<Long> others = jdbcTemplate.query(
|
||||
"SELECT id FROM sync_hub_book WHERE holder = ? AND (doc_id = ? OR match_key = ?) AND id <> ?",
|
||||
(rs, rowNum) -> rs.getLong(1), holder, key, key, id);
|
||||
if (!others.isEmpty()) {
|
||||
jdbcTemplate.update("DELETE FROM sync_hub_book WHERE id = ?", id);
|
||||
continue;
|
||||
}
|
||||
jdbcTemplate.update("UPDATE sync_hub_book SET doc_id = ?, match_key = ? WHERE id = ?", key, key, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.banben.modules.synchub.config;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/**
|
||||
* 校验同步口令。/api/hub 下的接口不使用登录令牌,必须带请求头 X-Hub-Token。
|
||||
* 值要和 application-dev.yml 里的 sync-hub.token 完全一致,开发环境是 local-mock-hub。
|
||||
* 没带这个头、或者值不一致,直接返回 401。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class HubTokenInterceptor implements HandlerInterceptor {
|
||||
|
||||
public static final String HEADER = "X-Hub-Token";
|
||||
|
||||
private final SyncHubProperties properties;
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
|
||||
return true;
|
||||
}
|
||||
String configured = properties.getToken() == null ? "" : properties.getToken();
|
||||
String given = request.getHeader(HEADER);
|
||||
if (configured.isBlank() || given == null || !MessageDigest.isEqual(configured.getBytes(StandardCharsets.UTF_8), given.getBytes(StandardCharsets.UTF_8))) {
|
||||
response.setStatus(401);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("{\"code\":401,\"message\":\"同步口令不正确,请在请求头 X-Hub-Token 中填写与 sync-hub.token 相同的值\"}");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.banben.modules.synchub.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 节点与南昌总库的同步配置。地址和口令都从这里读,不写死真实库账号。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "sync-hub")
|
||||
public class SyncHubProperties {
|
||||
|
||||
/** 两台电脑互相调用时放在请求头 X-Hub-Token */
|
||||
private String token = "";
|
||||
|
||||
/** es:写入 Elasticsearch;jdbc:写入 sync_hub_book,供本机没有 ES 时联调 */
|
||||
private String store = "es";
|
||||
|
||||
private String esUris = "http://127.0.0.1:9200";
|
||||
|
||||
private String esIndex = "book_metadata";
|
||||
|
||||
/** 节点把数据推到这个总库地址 */
|
||||
private String centerUrl = "http://127.0.0.1:8080";
|
||||
|
||||
/** 总库入库成功后是否立刻回传给各节点 */
|
||||
private boolean autoDispatch = true;
|
||||
|
||||
private int retryMax = 3;
|
||||
|
||||
/** 一次读取、接收或回传的条数。数据量大时按这个数分批,不一次全量传输。 */
|
||||
private int batchSize = 200;
|
||||
|
||||
/** 和 batchSize 同义,保留给旧配置。 */
|
||||
private int dispatchLimit = 200;
|
||||
|
||||
public int pageSize() {
|
||||
int size = batchSize > 0 ? batchSize : dispatchLimit;
|
||||
if (size < 1) {
|
||||
size = 200;
|
||||
}
|
||||
return Math.min(size, 1000);
|
||||
}
|
||||
|
||||
private List<Node> nodes = new ArrayList<>();
|
||||
|
||||
@Data
|
||||
public static class Node {
|
||||
private String code;
|
||||
private String name;
|
||||
/** MYSQL、SQLSERVER、MOCK,多个用逗号 */
|
||||
private String kinds = "MOCK";
|
||||
private String callbackUrl = "http://127.0.0.1:8080";
|
||||
private String mysqlUrl = "";
|
||||
private String mysqlUser = "";
|
||||
private String mysqlPassword = "";
|
||||
private String mysqlQuery = "";
|
||||
private String sqlserverUrl = "";
|
||||
private String sqlserverUser = "";
|
||||
private String sqlserverPassword = "";
|
||||
private String sqlserverQuery = "";
|
||||
}
|
||||
|
||||
public Node find(String code) {
|
||||
if (code == null) {
|
||||
return null;
|
||||
}
|
||||
return nodes.stream().filter(node -> code.equalsIgnoreCase(node.getCode())).findFirst().orElse(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package com.banben.modules.synchub.controller;
|
||||
|
||||
import com.banben.common.Result;
|
||||
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||
import com.banben.modules.synchub.entity.SyncHubRecord;
|
||||
import com.banben.modules.synchub.model.BookDocument;
|
||||
import com.banben.modules.synchub.service.SyncHubService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 节点与南昌总库的图书同步接口。
|
||||
*
|
||||
* <p>不使用登录令牌。每个请求都要加请求头 {@code X-Hub-Token},
|
||||
* 值与 {@code application-dev.yml} 的 {@code sync-hub.token} 相同。
|
||||
* 开发环境填 {@code local-mock-hub}。不带或填错返回 401。</p>
|
||||
*
|
||||
* <p>手工测试时优先调 {@code POST /api/hub/node/push}。
|
||||
* 总库收书、节点收书这两个地址是两台电脑互相调用时用的。</p>
|
||||
*/
|
||||
@Tag(name = "图书汇聚", description = "请求头 X-Hub-Token 必填。节点上推、总库接收入库、缺书回补")
|
||||
@RestController
|
||||
@RequestMapping("/api/hub")
|
||||
@RequiredArgsConstructor
|
||||
public class SyncHubController {
|
||||
|
||||
private final SyncHubService syncHubService;
|
||||
private final SyncHubProperties properties;
|
||||
|
||||
/**
|
||||
* 节点读一页本地图书并推到总库。
|
||||
* 总库按 ISBN(没有 ISBN 则按题名+作者+出版年)比对,重复的不入库。
|
||||
* 返回的 nextOffset 有值时,原样作为下一次的 offset 再调,直到它为空。
|
||||
*/
|
||||
@Operation(summary = "节点读取一页本地图书并推送到总库")
|
||||
@PostMapping("/node/push")
|
||||
public Result<SyncHubRecord> push(
|
||||
@Parameter(description = "节点编码。NJ_LZ 南京陆指,NJ_LGD 南京陆工大,BHF 边海防", required = true)
|
||||
@RequestParam String node,
|
||||
@Parameter(description = "从哪里读。MOCK 模拟数据;MYSQL 读该节点配置的 MySQL;SQLSERVER 读 SQL Server。不传默认 MOCK")
|
||||
@RequestParam(defaultValue = "MOCK") String source,
|
||||
@Parameter(description = "只推这一类书。纸质 或 电子。不传表示这一页里的书都推")
|
||||
@RequestParam(required = false) String media,
|
||||
@Parameter(description = "从第几条开始读,从 0 起。下一页把上次返回的 nextOffset 填到这里")
|
||||
@RequestParam(defaultValue = "0") int offset,
|
||||
@Parameter(description = "这一页最多几条。不传用 sync-hub.batch-size,默认 200,最大 1000")
|
||||
@RequestParam(required = false) Integer limit) {
|
||||
return Result.success(syncHubService.pushFromNode(node, source, media, offset, limit));
|
||||
}
|
||||
|
||||
/**
|
||||
* 总库接收入库。节点上推时会自己调用它,两台电脑联调时由对方机器调用。
|
||||
* 请求体字段:nodeCode 节点编码,sourceDb 来源库类型,books 图书数组。
|
||||
*/
|
||||
@Operation(summary = "总库接收节点推来的图书。重复的不入库,新的才入库")
|
||||
@PostMapping("/center/receive")
|
||||
public Result<SyncHubRecord> receive(@RequestBody SyncHubService.ReceiveBody body) {
|
||||
return Result.success(syncHubService.receiveAtCenter(body.nodeCode(), body.sourceDb(), body.books()));
|
||||
}
|
||||
|
||||
/** 总库检查每个节点还缺哪些书,只把缺的补过去。没有缺书的节点不会产生记录。 */
|
||||
@Operation(summary = "总库把节点还没有的书补回去")
|
||||
@PostMapping("/center/dispatch")
|
||||
public Result<List<SyncHubRecord>> dispatch() {
|
||||
return Result.success(syncHubService.dispatchAll());
|
||||
}
|
||||
|
||||
/**
|
||||
* 节点收下总库补来的书。节点里已经有的不再写,也不会再推回总库。
|
||||
* 请求体字段:nodeCode 收下的节点,books 要补进该节点的书。
|
||||
*/
|
||||
@Operation(summary = "节点接收总库补来的图书")
|
||||
@PostMapping("/node/receive")
|
||||
public Result<SyncHubRecord> receiveBack(@RequestBody SyncHubService.DeliverBody body) {
|
||||
return Result.success(syncHubService.receiveAtNode(body.nodeCode(), body.books()));
|
||||
}
|
||||
|
||||
/** 查看同步记录。bookCount 是新写入条数,skipCount 是重复跳过条数。 */
|
||||
@Operation(summary = "同步记录")
|
||||
@GetMapping("/record")
|
||||
public Result<List<SyncHubRecord>> records(
|
||||
@Parameter(description = "返回最近多少条,默认 50,最大 200")
|
||||
@RequestParam(defaultValue = "50") int limit) {
|
||||
return Result.success(syncHubService.listRecords(limit));
|
||||
}
|
||||
|
||||
/** 对一条失败记录再执行一次。已经成功或超过 maxRetry 的不能再试。 */
|
||||
@Operation(summary = "重试一条失败记录")
|
||||
@PostMapping("/record/{id}/retry")
|
||||
public Result<SyncHubRecord> retry(
|
||||
@Parameter(description = "同步记录的 id,从 /api/hub/record 的返回里取", required = true)
|
||||
@PathVariable Long id) {
|
||||
return Result.success(syncHubService.retry(id));
|
||||
}
|
||||
|
||||
/** 查看总库或某个节点已经收下的书,用来核对去重和回补结果。 */
|
||||
@Operation(summary = "查看总库或某个节点已经收下的图书")
|
||||
@GetMapping("/books")
|
||||
public Result<List<BookDocument>> books(
|
||||
@Parameter(description = "CENTER 总库;或节点编码 NJ_LZ、NJ_LGD、BHF。默认 CENTER")
|
||||
@RequestParam(defaultValue = "CENTER") String holder,
|
||||
@Parameter(description = "最多返回多少条,默认 20,最大 100")
|
||||
@RequestParam(defaultValue = "20") int limit) {
|
||||
return Result.success(syncHubService.listBooks(holder, limit));
|
||||
}
|
||||
|
||||
/** 只查看模拟图书,不推送、不入库。用来确认节点编码和模拟数据。 */
|
||||
@Operation(summary = "查看某个节点的模拟图书,不入库")
|
||||
@GetMapping("/mock/books")
|
||||
public Result<List<BookDocument>> mockBooks(
|
||||
@Parameter(description = "节点编码。NJ_LZ、NJ_LGD、BHF", required = true)
|
||||
@RequestParam String node,
|
||||
@Parameter(description = "只看这一类。纸质 或 电子。不传返回该节点的全部模拟书")
|
||||
@RequestParam(required = false) String media) {
|
||||
return Result.success(syncHubService.mockBooks(node, media));
|
||||
}
|
||||
|
||||
/** 节点清单。只返回编码、名称、库类型和回传地址,不含数据库账号。 */
|
||||
@Operation(summary = "节点清单,不含数据库口令")
|
||||
@GetMapping("/nodes")
|
||||
public Result<List<NodeView>> nodes() {
|
||||
List<NodeView> views = new ArrayList<>();
|
||||
for (SyncHubProperties.Node node : properties.getNodes()) {
|
||||
NodeView view = new NodeView();
|
||||
view.setCode(node.getCode());
|
||||
view.setName(node.getName());
|
||||
view.setKinds(node.getKinds());
|
||||
view.setCallbackUrl(node.getCallbackUrl());
|
||||
views.add(view);
|
||||
}
|
||||
return Result.success(views);
|
||||
}
|
||||
|
||||
/** 节点清单里的一项,不含数据库地址和口令。 */
|
||||
@Data
|
||||
public static class NodeView {
|
||||
/** 节点编码,调用 push 时传给 node */
|
||||
private String code;
|
||||
/** 节点名称,如南京陆工大 */
|
||||
private String name;
|
||||
/** 这个节点能读的库类型,多个用逗号分隔,如 MYSQL,SQLSERVER */
|
||||
private String kinds;
|
||||
/** 总库把缺书补回这个地址 */
|
||||
private String callbackUrl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.banben.modules.synchub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 一次同步的记录:谁发给谁、什么时候、成功还是失败。
|
||||
*/
|
||||
@Data
|
||||
@TableName("sync_hub_record")
|
||||
public class SyncHubRecord {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
/** 本次同步编号,排查日志时用 */
|
||||
private String taskNo;
|
||||
|
||||
/** UP:节点推总库。DOWN:总库把缺的书补回节点 */
|
||||
private String direction;
|
||||
|
||||
/** 数据从哪个节点发出。总库回传时是 NC_CENTER */
|
||||
private String sourceNode;
|
||||
|
||||
/** 数据送到哪里。上推时是 NC_CENTER,回传时是节点编码 */
|
||||
private String targetNode;
|
||||
|
||||
/** 读取来源:MOCK、MYSQL、SQLSERVER,回传时为 CENTER */
|
||||
private String sourceDb;
|
||||
|
||||
/** 这次新写入的条数 */
|
||||
private Integer bookCount;
|
||||
|
||||
/** 比对后已存在、没有写入的条数 */
|
||||
private Integer skipCount;
|
||||
|
||||
/** RUNNING 进行中,SUCCESS 成功,FAILED 失败 */
|
||||
private String status;
|
||||
|
||||
/** 失败原因。成功且还有下一批回传时,这里会提示再调一次回传接口 */
|
||||
private String errorMessage;
|
||||
|
||||
/** 已经重试过几次 */
|
||||
private Integer retryCount;
|
||||
|
||||
/** 最多还能重试几次,默认 3 */
|
||||
private Integer maxRetry;
|
||||
|
||||
private LocalDateTime startTime;
|
||||
|
||||
private LocalDateTime endTime;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/** 源库还有下一批时返回,调用方用它继续取。不入库。 */
|
||||
@TableField(exist = false)
|
||||
private Integer nextOffset;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.banben.modules.synchub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.banben.modules.synchub.entity.SyncHubRecord;
|
||||
|
||||
public interface SyncHubRecordMapper extends BaseMapper<SyncHubRecord> {
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.banben.modules.synchub.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 在节点和总库之间传递的一条图书元数据。字段与 version_resource 的书目项对应,不直接改那张表。
|
||||
*/
|
||||
@Data
|
||||
public class BookDocument {
|
||||
|
||||
private String nodeCode;
|
||||
|
||||
/** MYSQL / SQLSERVER / MOCK */
|
||||
private String sourceDb;
|
||||
|
||||
private String processNo;
|
||||
|
||||
private String title;
|
||||
|
||||
private String author;
|
||||
|
||||
private String isbn;
|
||||
|
||||
private String publisher;
|
||||
|
||||
private String publishYear;
|
||||
|
||||
private String keywords;
|
||||
|
||||
private String summary;
|
||||
|
||||
private String clcCode;
|
||||
|
||||
private String mediaType;
|
||||
|
||||
private String language;
|
||||
|
||||
private String contentForm;
|
||||
|
||||
private String sourceLibrary;
|
||||
|
||||
private String fulltextUrl;
|
||||
|
||||
@JsonIgnore
|
||||
public String docId() {
|
||||
String node = nodeCode == null ? "NODE" : nodeCode.trim();
|
||||
String no = processNo == null || processNo.isBlank() ? title : processNo.trim();
|
||||
return node + ":" + no;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.banben.modules.synchub.reader;
|
||||
|
||||
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||
import com.banben.modules.synchub.model.BookDocument;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 从分支节点的本地库读取图书。MOCK、MYSQL、SQLSERVER 各有一个实现。
|
||||
*/
|
||||
public interface BookReader {
|
||||
|
||||
boolean supports(String source);
|
||||
|
||||
List<BookDocument> read(SyncHubProperties.Node node, String mediaType);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.banben.modules.synchub.reader;
|
||||
|
||||
import com.banben.common.BusinessException;
|
||||
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||
import com.banben.modules.synchub.model.BookDocument;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 按节点配置读取 MySQL 或 SQL Server。地址没配时直接拒绝,不会去连测试机。
|
||||
*/
|
||||
@Component
|
||||
public class JdbcRemoteBookReader implements BookReader {
|
||||
|
||||
@Override
|
||||
public boolean supports(String source) {
|
||||
return "MYSQL".equalsIgnoreCase(source) || "SQLSERVER".equalsIgnoreCase(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookDocument> read(SyncHubProperties.Node node, String mediaType) {
|
||||
throw new BusinessException("请指定 MYSQL 或 SQLSERVER");
|
||||
}
|
||||
|
||||
public List<BookDocument> read(SyncHubProperties.Node node, String source, String mediaType) {
|
||||
return readPage(node, source, mediaType, 0, 200).books();
|
||||
}
|
||||
|
||||
/** 按 offset 取一页。more 为 true 表示后面还有,调用方继续传下一个 offset。 */
|
||||
public Page readPage(SyncHubProperties.Node node, String source, String mediaType, int offset, int limit) {
|
||||
boolean mysql = "MYSQL".equalsIgnoreCase(source);
|
||||
String url = mysql ? node.getMysqlUrl() : node.getSqlserverUrl();
|
||||
String user = mysql ? node.getMysqlUser() : node.getSqlserverUser();
|
||||
String password = mysql ? node.getMysqlPassword() : node.getSqlserverPassword();
|
||||
String query = mysql ? node.getMysqlQuery() : node.getSqlserverQuery();
|
||||
if (url == null || url.isBlank() || query == null || query.isBlank()) {
|
||||
throw new BusinessException(node.getName() + " 还没配置 " + source + " 的地址和查询。本地联调请传 source=MOCK");
|
||||
}
|
||||
String sql = query.trim();
|
||||
if (sql.endsWith(";")) {
|
||||
sql = sql.substring(0, sql.length() - 1).trim();
|
||||
}
|
||||
String head = sql.toLowerCase(Locale.ROOT);
|
||||
if ((!head.startsWith("select") && !head.startsWith("with")) || sql.indexOf(';') >= 0) {
|
||||
throw new BusinessException("节点查询只能是一条 SELECT");
|
||||
}
|
||||
try {
|
||||
Class.forName(mysql ? "com.mysql.cj.jdbc.Driver" : "com.microsoft.sqlserver.jdbc.SQLServerDriver");
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new BusinessException("缺少 " + source + " 驱动");
|
||||
}
|
||||
int size = limit < 1 ? 200 : Math.min(limit, 1000);
|
||||
int start = Math.max(offset, 0);
|
||||
String pageSql = pageSql(sql, mysql, start, size);
|
||||
List<BookDocument> books = new ArrayList<>();
|
||||
int raw = 0;
|
||||
try (Connection connection = DriverManager.getConnection(url, user, password);
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.setQueryTimeout(20);
|
||||
try (ResultSet rs = statement.executeQuery(pageSql)) {
|
||||
Map<String, Integer> labels = labels(rs.getMetaData());
|
||||
while (rs.next()) {
|
||||
raw++;
|
||||
BookDocument book = mapRow(node, source, rs, labels);
|
||||
if (mediaType != null && !mediaType.isBlank() && !"ALL".equalsIgnoreCase(mediaType)
|
||||
&& book.getMediaType() != null && !mediaType.equals(book.getMediaType())) {
|
||||
continue;
|
||||
}
|
||||
books.add(book);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String message = e.getMessage() == null ? "读取失败" : e.getMessage();
|
||||
if (password != null && !password.isBlank()) {
|
||||
message = message.replace(password, "******");
|
||||
}
|
||||
throw new BusinessException("读取 " + node.getName() + " 失败:" + message);
|
||||
}
|
||||
return new Page(books, raw >= size && !alreadyPaged(sql));
|
||||
}
|
||||
|
||||
private String pageSql(String sql, boolean mysql, int offset, int limit) {
|
||||
if (alreadyPaged(sql)) {
|
||||
return offset > 0 ? "SELECT * FROM (" + sql + ") hub_src WHERE 1 = 0" : sql;
|
||||
}
|
||||
if (mysql) {
|
||||
return "SELECT * FROM (" + sql + ") hub_src LIMIT " + limit + " OFFSET " + offset;
|
||||
}
|
||||
return "SELECT * FROM (" + sql + ") hub_src ORDER BY (SELECT 1) OFFSET " + offset
|
||||
+ " ROWS FETCH NEXT " + limit + " ROWS ONLY";
|
||||
}
|
||||
|
||||
private boolean alreadyPaged(String sql) {
|
||||
String text = sql.toLowerCase(Locale.ROOT);
|
||||
return text.contains(" limit ") || text.contains(" offset ") || text.contains(" fetch ") || text.contains(" top ");
|
||||
}
|
||||
|
||||
/** 一页读取结果。more 表示这一页被取满,源库后面可能还有。 */
|
||||
public record Page(List<BookDocument> books, boolean more) {
|
||||
}
|
||||
|
||||
private Map<String, Integer> labels(ResultSetMetaData meta) throws SQLException {
|
||||
Map<String, Integer> labels = new LinkedHashMap<>();
|
||||
for (int i = 1; i <= meta.getColumnCount(); i++) {
|
||||
labels.put(meta.getColumnLabel(i).toLowerCase(Locale.ROOT), i);
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
private BookDocument mapRow(SyncHubProperties.Node node, String source, ResultSet rs, Map<String, Integer> labels) throws SQLException {
|
||||
BookDocument book = new BookDocument();
|
||||
book.setNodeCode(node.getCode());
|
||||
book.setSourceDb(source.toUpperCase(Locale.ROOT));
|
||||
book.setProcessNo(text(rs, labels, "process_no", "processno", "record_id", "recordid"));
|
||||
book.setTitle(text(rs, labels, "title", "book_name", "name"));
|
||||
book.setAuthor(text(rs, labels, "author"));
|
||||
book.setIsbn(text(rs, labels, "isbn", "isbn13", "isbn_13", "e_isbn", "eisbn"));
|
||||
book.setPublisher(text(rs, labels, "publisher"));
|
||||
book.setPublishYear(text(rs, labels, "publish_year", "publishyear", "pub_year"));
|
||||
book.setKeywords(text(rs, labels, "keywords", "subject"));
|
||||
book.setSummary(text(rs, labels, "summary", "description"));
|
||||
book.setClcCode(text(rs, labels, "clc_code", "clc", "call_no"));
|
||||
book.setMediaType(text(rs, labels, "media_type", "mediatype"));
|
||||
book.setLanguage(text(rs, labels, "language"));
|
||||
book.setContentForm(text(rs, labels, "content_form"));
|
||||
book.setSourceLibrary(firstNonBlank(text(rs, labels, "source_library"), node.getName()));
|
||||
book.setFulltextUrl(text(rs, labels, "fulltext_url", "find_jump_url"));
|
||||
if (book.getProcessNo() == null || book.getProcessNo().isBlank()) {
|
||||
book.setProcessNo(node.getCode() + "-" + (book.getIsbn() == null ? book.getTitle() : book.getIsbn()));
|
||||
}
|
||||
return book;
|
||||
}
|
||||
|
||||
private String text(ResultSet rs, Map<String, Integer> labels, String... names) throws SQLException {
|
||||
for (String name : names) {
|
||||
Integer index = labels.get(name.toLowerCase(Locale.ROOT));
|
||||
if (index != null) {
|
||||
String value = rs.getString(index);
|
||||
if (value != null && !value.isBlank()) {
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String firstNonBlank(String value, String fallback) {
|
||||
return value == null || value.isBlank() ? fallback : value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.banben.modules.synchub.reader;
|
||||
|
||||
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||
import com.banben.modules.synchub.model.BookDocument;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 本地联调用的模拟图书。不连接陆工大、陆指或边海防的真实库。
|
||||
*/
|
||||
@Component
|
||||
public class MockBookReader implements BookReader {
|
||||
|
||||
@Override
|
||||
public boolean supports(String source) {
|
||||
return "MOCK".equalsIgnoreCase(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookDocument> read(SyncHubProperties.Node node, String mediaType) {
|
||||
List<BookDocument> all = samples(node);
|
||||
if (mediaType == null || mediaType.isBlank() || "ALL".equalsIgnoreCase(mediaType)) {
|
||||
return all;
|
||||
}
|
||||
return all.stream().filter(book -> mediaType.equals(book.getMediaType())).toList();
|
||||
}
|
||||
|
||||
private List<BookDocument> samples(SyncHubProperties.Node node) {
|
||||
String code = node.getCode() == null ? "" : node.getCode().toUpperCase();
|
||||
List<BookDocument> books = new ArrayList<>();
|
||||
if ("NJ_LGD".equals(code)) {
|
||||
books.add(book(node, "MYSQL", "LGD-P-001", "陆军工程概要", "纸质", "9787300000001"));
|
||||
books.add(book(node, "SQLSERVER", "LGD-E-001", "工程力学电子版", "电子", "9787300000002"));
|
||||
return books;
|
||||
}
|
||||
if ("NJ_LZ".equals(code)) {
|
||||
books.add(book(node, "MYSQL", "LZ-P-001", "指挥学基础", "纸质", "9787300000011"));
|
||||
return books;
|
||||
}
|
||||
books.add(book(node, "MOCK", code + "-P-001", node.getName() + "样例图书", "纸质", "9787300000099"));
|
||||
return books;
|
||||
}
|
||||
|
||||
private BookDocument book(SyncHubProperties.Node node, String sourceDb, String processNo, String title, String media, String isbn) {
|
||||
BookDocument book = new BookDocument();
|
||||
book.setNodeCode(node.getCode());
|
||||
book.setSourceDb(sourceDb);
|
||||
book.setProcessNo(processNo);
|
||||
book.setTitle(title);
|
||||
book.setAuthor("模拟作者");
|
||||
book.setIsbn(isbn);
|
||||
book.setPublisher("模拟出版社");
|
||||
book.setPublishYear("2024");
|
||||
book.setMediaType(media);
|
||||
book.setLanguage("chi");
|
||||
book.setSourceLibrary(node.getName());
|
||||
book.setKeywords("联调");
|
||||
book.setSummary("本地模拟数据,不是现场馆藏。");
|
||||
return book;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.banben.modules.synchub.service;
|
||||
|
||||
import com.banben.modules.synchub.model.BookDocument;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 图书比对。节点推上来的书和总库比,推送库再和总库比,重复的留下,没有的才入库。
|
||||
*/
|
||||
@Component
|
||||
public class BookCleaner {
|
||||
|
||||
/**
|
||||
* 从待入库列表里去掉已经有的书。
|
||||
* 有 ISBN 时按 ISBN 判断;没有 ISBN 时按题名、作者、出版年一起判断。
|
||||
* 同一批里相同的书也只留第一条。
|
||||
*/
|
||||
public List<BookDocument> clean(List<BookDocument> incoming, Collection<String> heldKeys) {
|
||||
Set<String> seen = new HashSet<>();
|
||||
if (heldKeys != null) {
|
||||
seen.addAll(heldKeys);
|
||||
}
|
||||
List<BookDocument> fresh = new ArrayList<>();
|
||||
if (incoming == null) {
|
||||
return fresh;
|
||||
}
|
||||
for (BookDocument book : incoming) {
|
||||
tidy(book);
|
||||
if (seen.add(matchKey(book))) {
|
||||
fresh.add(book);
|
||||
}
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
|
||||
/** 同一本书用同一个比对键,不看它来自哪个节点。 */
|
||||
public String matchKey(BookDocument book) {
|
||||
String isbn = digits(book == null ? null : book.getIsbn());
|
||||
if (!isbn.isEmpty()) {
|
||||
return cut("isbn:" + isbn);
|
||||
}
|
||||
String title = norm(book == null ? null : book.getTitle());
|
||||
String author = norm(book == null ? null : book.getAuthor());
|
||||
String year = norm(book == null ? null : book.getPublishYear());
|
||||
return cut("meta:" + title + "|" + author + "|" + year);
|
||||
}
|
||||
|
||||
public Set<String> keysOf(List<BookDocument> books) {
|
||||
Set<String> keys = new HashSet<>();
|
||||
if (books == null) {
|
||||
return keys;
|
||||
}
|
||||
for (BookDocument book : books) {
|
||||
keys.add(matchKey(book));
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
private void tidy(BookDocument book) {
|
||||
if (book == null) {
|
||||
return;
|
||||
}
|
||||
if (book.getTitle() != null) {
|
||||
book.setTitle(book.getTitle().trim());
|
||||
}
|
||||
if (book.getIsbn() != null) {
|
||||
book.setIsbn(book.getIsbn().trim());
|
||||
}
|
||||
}
|
||||
|
||||
private String digits(String isbn) {
|
||||
if (isbn == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (int i = 0; i < isbn.length(); i++) {
|
||||
char c = isbn.charAt(i);
|
||||
if (c >= '0' && c <= '9') {
|
||||
out.append(c);
|
||||
} else if (c == 'X' || c == 'x') {
|
||||
out.append('x');
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private String norm(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
return value.trim().replaceAll("\\s+", "").toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private String cut(String key) {
|
||||
return key.length() <= 300 ? key : key.substring(0, 300);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
package com.banben.modules.synchub.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.banben.common.BusinessException;
|
||||
import com.banben.modules.synchub.config.HubTokenInterceptor;
|
||||
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||
import com.banben.modules.synchub.entity.SyncHubRecord;
|
||||
import com.banben.modules.synchub.mapper.SyncHubRecordMapper;
|
||||
import com.banben.modules.synchub.model.BookDocument;
|
||||
import com.banben.modules.synchub.reader.JdbcRemoteBookReader;
|
||||
import com.banben.modules.synchub.reader.MockBookReader;
|
||||
import com.banben.modules.synchub.store.BookStore;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 分支节点把图书推到南昌总库。总库只收新书,再把总库里该节点还没有的书补回去。
|
||||
* 数据量大时按 batch-size 分批,不一次传输全库。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class SyncHubService {
|
||||
|
||||
public static final String CENTER = "CENTER";
|
||||
public static final String UP = "UP";
|
||||
public static final String DOWN = "DOWN";
|
||||
|
||||
private final SyncHubProperties properties;
|
||||
private final BookCleaner cleaner;
|
||||
private final BookStore bookStore;
|
||||
private final MockBookReader mockBookReader;
|
||||
private final JdbcRemoteBookReader remoteBookReader;
|
||||
private final SyncHubRecordMapper recordMapper;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(8)).build();
|
||||
|
||||
/** 节点读取一页本地图书,推到总库。返回的 nextOffset 有值时,用它继续取下一页。 */
|
||||
public SyncHubRecord pushFromNode(String nodeCode, String source, String mediaType, int offset, Integer limit) {
|
||||
SyncHubProperties.Node node = requireNode(nodeCode);
|
||||
int size = limit == null || limit < 1 ? properties.pageSize() : Math.min(limit, 1000);
|
||||
int start = Math.max(offset, 0);
|
||||
SyncHubRecord record = open(UP, node.getCode(), "NC_CENTER", source);
|
||||
try {
|
||||
JdbcRemoteBookReader.Page page = readPage(node, source, mediaType, start, size);
|
||||
if (page.books().isEmpty()) {
|
||||
if (start == 0) {
|
||||
throw new BusinessException("没有图书数据");
|
||||
}
|
||||
record.setBookCount(0);
|
||||
record.setSkipCount(0);
|
||||
succeed(record);
|
||||
return record;
|
||||
}
|
||||
List<BookDocument> books = prepare(page.books(), node.getCode(), source);
|
||||
JsonNode data = post(join(properties.getCenterUrl(), "/api/hub/center/receive"), new ReceiveBody(node.getCode(), source, books));
|
||||
record.setBookCount(data.path("bookCount").asInt(0));
|
||||
record.setSkipCount(data.path("skipCount").asInt(0));
|
||||
if (page.more()) {
|
||||
record.setNextOffset(start + size);
|
||||
}
|
||||
succeed(record);
|
||||
return record;
|
||||
} catch (Exception e) {
|
||||
fail(record, e);
|
||||
throw new BusinessException(record.getErrorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** 总库收到节点推来的图书。和总库已有书比对,重复的不入库,新的才入库,然后给还缺书的节点补回。 */
|
||||
public SyncHubRecord receiveAtCenter(String nodeCode, String sourceDb, List<BookDocument> books) {
|
||||
SyncHubRecord record = open(UP, nodeCode, "NC_CENTER", sourceDb);
|
||||
try {
|
||||
List<BookDocument> prepared = prepare(books, nodeCode, sourceDb);
|
||||
guardSize(prepared);
|
||||
List<BookDocument> fresh = cleaner.clean(prepared, bookStore.existingKeys(CENTER, cleaner.keysOf(prepared)));
|
||||
int inserted = fresh.isEmpty() ? 0 : bookStore.saveNew(CENTER, fresh);
|
||||
record.setBookCount(inserted);
|
||||
record.setSkipCount(prepared.size() - inserted);
|
||||
succeed(record);
|
||||
} catch (Exception e) {
|
||||
fail(record, e);
|
||||
throw new BusinessException(record.getErrorMessage());
|
||||
}
|
||||
if (properties.isAutoDispatch()) {
|
||||
dispatchAll();
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
/** 总库把各节点还没有的书补过去。一次最多回传 20 批,没传完就再调一次。 */
|
||||
public List<SyncHubRecord> dispatchAll() {
|
||||
List<SyncHubRecord> records = new ArrayList<>();
|
||||
for (SyncHubProperties.Node node : properties.getNodes()) {
|
||||
SyncHubRecord record = dispatchMissing(node);
|
||||
if (record != null) {
|
||||
records.add(record);
|
||||
}
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
/** 节点收下总库补来的书。节点里已经有的不再写入,也不再往总库推。 */
|
||||
public SyncHubRecord receiveAtNode(String nodeCode, List<BookDocument> books) {
|
||||
SyncHubProperties.Node node = requireNode(nodeCode);
|
||||
SyncHubRecord record = open(DOWN, "NC_CENTER", node.getCode(), "CENTER");
|
||||
try {
|
||||
List<BookDocument> prepared = prepare(books, null, null);
|
||||
guardSize(prepared);
|
||||
List<BookDocument> fresh = cleaner.clean(prepared, bookStore.existingKeys(node.getCode(), cleaner.keysOf(prepared)));
|
||||
int inserted = fresh.isEmpty() ? 0 : bookStore.saveNew(node.getCode(), fresh);
|
||||
record.setBookCount(inserted);
|
||||
record.setSkipCount(prepared.size() - inserted);
|
||||
succeed(record);
|
||||
return record;
|
||||
} catch (Exception e) {
|
||||
fail(record, e);
|
||||
throw new BusinessException(record.getErrorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public List<BookDocument> mockBooks(String nodeCode, String mediaType) {
|
||||
return mockBookReader.read(requireNode(nodeCode), mediaType);
|
||||
}
|
||||
|
||||
public List<BookDocument> listBooks(String holder, int limit) {
|
||||
String code = holder == null || holder.isBlank() ? CENTER : holder.trim();
|
||||
if (!CENTER.equalsIgnoreCase(code) && properties.find(code) == null) {
|
||||
throw new BusinessException("未知节点:" + code);
|
||||
}
|
||||
int size = limit <= 0 ? 20 : Math.min(limit, 100);
|
||||
return bookStore.findAll(code, size);
|
||||
}
|
||||
|
||||
public List<SyncHubRecord> listRecords(int limit) {
|
||||
int size = limit <= 0 ? 50 : Math.min(limit, 200);
|
||||
return recordMapper.selectList(new LambdaQueryWrapper<SyncHubRecord>()
|
||||
.orderByDesc(SyncHubRecord::getId)
|
||||
.last("LIMIT " + size));
|
||||
}
|
||||
|
||||
/** 失败记录再跑一次。上推会重新读取,回传会重新读取总库已保存的数据。 */
|
||||
public SyncHubRecord retry(Long id) {
|
||||
SyncHubRecord record = recordMapper.selectById(id);
|
||||
if (record == null) {
|
||||
throw new BusinessException("同步记录不存在");
|
||||
}
|
||||
if ("SUCCESS".equals(record.getStatus())) {
|
||||
throw new BusinessException("这条记录已经成功");
|
||||
}
|
||||
int used = record.getRetryCount() == null ? 0 : record.getRetryCount();
|
||||
int max = record.getMaxRetry() == null ? properties.getRetryMax() : record.getMaxRetry();
|
||||
if (used >= max) {
|
||||
throw new BusinessException("已达到重试次数");
|
||||
}
|
||||
record.setRetryCount(used + 1);
|
||||
record.setStatus("RUNNING");
|
||||
record.setErrorMessage(null);
|
||||
record.setStartTime(LocalDateTime.now());
|
||||
recordMapper.updateById(record);
|
||||
try {
|
||||
if (UP.equals(record.getDirection())) {
|
||||
SyncHubProperties.Node node = requireNode(record.getSourceNode());
|
||||
JdbcRemoteBookReader.Page page = readPage(node, record.getSourceDb(), null, 0, properties.pageSize());
|
||||
if (page.books().isEmpty()) {
|
||||
throw new BusinessException("没有图书数据");
|
||||
}
|
||||
List<BookDocument> books = prepare(page.books(), node.getCode(), record.getSourceDb());
|
||||
JsonNode data = post(join(properties.getCenterUrl(), "/api/hub/center/receive"), new ReceiveBody(node.getCode(), record.getSourceDb(), books));
|
||||
record.setBookCount(data.path("bookCount").asInt(0));
|
||||
record.setSkipCount(data.path("skipCount").asInt(0));
|
||||
} else {
|
||||
SyncHubProperties.Node node = requireNode(record.getTargetNode());
|
||||
List<BookDocument> books = bookStore.findMissing(CENTER, node.getCode(), properties.pageSize());
|
||||
if (!books.isEmpty()) {
|
||||
post(join(node.getCallbackUrl(), "/api/hub/node/receive"), new DeliverBody(node.getCode(), books));
|
||||
}
|
||||
record.setBookCount(books.size());
|
||||
record.setSkipCount(0);
|
||||
}
|
||||
succeed(record);
|
||||
return record;
|
||||
} catch (Exception e) {
|
||||
fail(record, e);
|
||||
throw new BusinessException(record.getErrorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void retryQuiet(Long id) {
|
||||
try {
|
||||
retry(id);
|
||||
} catch (Exception e) {
|
||||
log.warn("同步重试未成功:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private SyncHubRecord dispatchMissing(SyncHubProperties.Node node) {
|
||||
int size = properties.pageSize();
|
||||
List<BookDocument> missing = bookStore.findMissing(CENTER, node.getCode(), size);
|
||||
if (missing.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
SyncHubRecord record = open(DOWN, "NC_CENTER", node.getCode(), "CENTER");
|
||||
int sent = 0;
|
||||
int pages = 0;
|
||||
boolean more = false;
|
||||
try {
|
||||
while (!missing.isEmpty()) {
|
||||
post(join(node.getCallbackUrl(), "/api/hub/node/receive"), new DeliverBody(node.getCode(), missing));
|
||||
sent += missing.size();
|
||||
pages++;
|
||||
if (missing.size() < size) {
|
||||
break;
|
||||
}
|
||||
if (pages >= 20) {
|
||||
more = true;
|
||||
break;
|
||||
}
|
||||
missing = bookStore.findMissing(CENTER, node.getCode(), size);
|
||||
}
|
||||
record.setBookCount(sent);
|
||||
record.setSkipCount(0);
|
||||
if (more) {
|
||||
record.setErrorMessage("还有未回传的数据,请再调用一次回传接口");
|
||||
}
|
||||
succeed(record);
|
||||
} catch (Exception e) {
|
||||
record.setBookCount(sent);
|
||||
fail(record, e);
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
private JdbcRemoteBookReader.Page readPage(SyncHubProperties.Node node, String source, String mediaType, int offset, int limit) {
|
||||
if (source == null || source.isBlank() || "MOCK".equalsIgnoreCase(source)) {
|
||||
List<BookDocument> all = new ArrayList<>(mockBookReader.read(node, mediaType));
|
||||
if (offset >= all.size()) {
|
||||
return new JdbcRemoteBookReader.Page(List.of(), false);
|
||||
}
|
||||
int end = Math.min(offset + limit, all.size());
|
||||
return new JdbcRemoteBookReader.Page(new ArrayList<>(all.subList(offset, end)), end < all.size());
|
||||
}
|
||||
if (remoteBookReader.supports(source)) {
|
||||
return remoteBookReader.readPage(node, source, mediaType, offset, limit);
|
||||
}
|
||||
throw new BusinessException("不支持的来源:" + source);
|
||||
}
|
||||
|
||||
private List<BookDocument> prepare(List<BookDocument> books, String nodeCode, String sourceDb) {
|
||||
if (books == null || books.isEmpty()) {
|
||||
throw new BusinessException("没有图书数据");
|
||||
}
|
||||
for (BookDocument book : books) {
|
||||
if (nodeCode != null && (book.getNodeCode() == null || book.getNodeCode().isBlank())) {
|
||||
book.setNodeCode(nodeCode);
|
||||
}
|
||||
if (sourceDb != null && (book.getSourceDb() == null || book.getSourceDb().isBlank())) {
|
||||
book.setSourceDb(sourceDb);
|
||||
}
|
||||
if (book.getTitle() == null || book.getTitle().isBlank()) {
|
||||
throw new BusinessException("图书缺少题名");
|
||||
}
|
||||
}
|
||||
return books;
|
||||
}
|
||||
|
||||
private void guardSize(List<BookDocument> books) {
|
||||
if (books.size() > 1000) {
|
||||
throw new BusinessException("单次最多接收 1000 条。数据量大时请按 offset 分批推送,每批不超过 " + properties.pageSize() + " 条");
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode post(String url, Object body) throws Exception {
|
||||
String json = objectMapper.writeValueAsString(body);
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Content-Type", "application/json")
|
||||
.header(HubTokenInterceptor.HEADER, properties.getToken() == null ? "" : properties.getToken())
|
||||
.POST(HttpRequest.BodyPublishers.ofString(json))
|
||||
.build();
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() != 200) {
|
||||
throw new BusinessException("对方返回 " + response.statusCode());
|
||||
}
|
||||
JsonNode root = objectMapper.readTree(response.body());
|
||||
if (root.path("code").asInt() != 200) {
|
||||
String message = root.path("message").asText("同步失败");
|
||||
throw new BusinessException(message);
|
||||
}
|
||||
return root.path("data");
|
||||
}
|
||||
|
||||
private SyncHubProperties.Node requireNode(String code) {
|
||||
SyncHubProperties.Node node = properties.find(code);
|
||||
if (node == null) {
|
||||
throw new BusinessException("未知节点:" + code);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private SyncHubRecord open(String direction, String sourceNode, String targetNode, String sourceDb) {
|
||||
SyncHubRecord record = new SyncHubRecord();
|
||||
record.setTaskNo(UUID.randomUUID().toString().replace("-", ""));
|
||||
record.setDirection(direction);
|
||||
record.setSourceNode(sourceNode);
|
||||
record.setTargetNode(targetNode);
|
||||
record.setSourceDb(sourceDb);
|
||||
record.setBookCount(0);
|
||||
record.setSkipCount(0);
|
||||
record.setStatus("RUNNING");
|
||||
record.setRetryCount(0);
|
||||
record.setMaxRetry(properties.getRetryMax());
|
||||
record.setStartTime(LocalDateTime.now());
|
||||
record.setCreateTime(LocalDateTime.now());
|
||||
recordMapper.insert(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
private void succeed(SyncHubRecord record) {
|
||||
record.setStatus("SUCCESS");
|
||||
if (record.getErrorMessage() == null || record.getErrorMessage().isBlank()) {
|
||||
record.setErrorMessage("");
|
||||
}
|
||||
record.setEndTime(LocalDateTime.now());
|
||||
recordMapper.updateById(record);
|
||||
log.info("图书同步成功 {} {} -> {} 共 {} 条", record.getTaskNo(), record.getSourceNode(), record.getTargetNode(), record.getBookCount());
|
||||
}
|
||||
|
||||
private void fail(SyncHubRecord record, Exception e) {
|
||||
String message = e.getMessage() == null ? "同步失败" : e.getMessage();
|
||||
if (message.length() > 1000) {
|
||||
message = message.substring(0, 1000);
|
||||
}
|
||||
record.setStatus("FAILED");
|
||||
record.setErrorMessage(message);
|
||||
record.setEndTime(LocalDateTime.now());
|
||||
recordMapper.updateById(record);
|
||||
log.warn("图书同步失败 {}:{}", record.getTaskNo(), message);
|
||||
}
|
||||
|
||||
private String join(String base, String path) {
|
||||
String root = base == null ? "" : base.trim();
|
||||
if (root.endsWith("/")) {
|
||||
root = root.substring(0, root.length() - 1);
|
||||
}
|
||||
return root + path;
|
||||
}
|
||||
|
||||
/**
|
||||
* 节点推给总库的报文,对应 POST /api/hub/center/receive。
|
||||
*
|
||||
* @param nodeCode 发出数据的节点编码,如 NJ_LGD
|
||||
* @param sourceDb 这批书从哪类库读出:MOCK、MYSQL、SQLSERVER
|
||||
* @param books 这一页图书。单次最多 1000 条
|
||||
*/
|
||||
public record ReceiveBody(String nodeCode, String sourceDb, List<BookDocument> books) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 总库补回给节点的报文,对应 POST /api/hub/node/receive。
|
||||
*
|
||||
* @param nodeCode 收下这批书的节点编码
|
||||
* @param books 总库有、该节点还没有的书
|
||||
*/
|
||||
public record DeliverBody(String nodeCode, List<BookDocument> books) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.banben.modules.synchub.store;
|
||||
|
||||
import com.banben.modules.synchub.model.BookDocument;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 图书汇总的存放位置。总库用 holder=CENTER,节点收到回传后用自己的节点编码。
|
||||
*/
|
||||
public interface BookStore {
|
||||
|
||||
/** 只插入还没有的书,返回真正新增的条数。已有的不覆盖。 */
|
||||
int saveNew(String holder, List<BookDocument> books);
|
||||
|
||||
/** 这批比对键里,库中已经存在的那些。 */
|
||||
Set<String> existingKeys(String holder, Collection<String> keys);
|
||||
|
||||
/** 源库有、目标库没有的书,一次最多返回 limit 条。 */
|
||||
List<BookDocument> findMissing(String sourceHolder, String targetHolder, int limit);
|
||||
|
||||
List<BookDocument> findAll(String holder, int limit);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package com.banben.modules.synchub.store;
|
||||
|
||||
import co.elastic.clients.elasticsearch.ElasticsearchClient;
|
||||
import co.elastic.clients.elasticsearch._types.FieldValue;
|
||||
import co.elastic.clients.elasticsearch._types.SortOrder;
|
||||
import co.elastic.clients.elasticsearch.core.BulkResponse;
|
||||
import co.elastic.clients.elasticsearch.core.MgetResponse;
|
||||
import co.elastic.clients.elasticsearch.core.SearchResponse;
|
||||
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
|
||||
import co.elastic.clients.elasticsearch.core.mget.MultiGetResponseItem;
|
||||
import co.elastic.clients.elasticsearch.core.search.Hit;
|
||||
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
|
||||
import co.elastic.clients.transport.rest_client.RestClientTransport;
|
||||
import com.banben.common.BusinessException;
|
||||
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||
import com.banben.modules.synchub.model.BookDocument;
|
||||
import com.banben.modules.synchub.service.BookCleaner;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.elasticsearch.client.RestClient;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 南昌总库的 Elasticsearch 写入和读取。文档编号用比对键,已存在的不覆盖。
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "sync-hub.store", havingValue = "es")
|
||||
public class EsBookStore implements BookStore {
|
||||
|
||||
private final SyncHubProperties properties;
|
||||
private final BookCleaner cleaner;
|
||||
private final RestClient restClient;
|
||||
private final ElasticsearchClient client;
|
||||
|
||||
public EsBookStore(SyncHubProperties properties, BookCleaner cleaner) {
|
||||
this.properties = properties;
|
||||
this.cleaner = cleaner;
|
||||
this.restClient = RestClient.builder(HttpHost.create(properties.getEsUris())).build();
|
||||
this.client = new ElasticsearchClient(new RestClientTransport(restClient, new JacksonJsonpMapper()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int saveNew(String holder, List<BookDocument> books) {
|
||||
if (books == null || books.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
ensureIndex(holder);
|
||||
List<BulkOperation> operations = new ArrayList<>();
|
||||
for (BookDocument book : books) {
|
||||
String key = cleaner.matchKey(book);
|
||||
operations.add(BulkOperation.of(op -> op.create(c -> c.index(index(holder)).id(key).document(book))));
|
||||
}
|
||||
try {
|
||||
BulkResponse response = client.bulk(b -> b.operations(operations));
|
||||
int inserted = 0;
|
||||
for (var item : response.items()) {
|
||||
if (item.error() == null) {
|
||||
inserted++;
|
||||
}
|
||||
}
|
||||
return inserted;
|
||||
} catch (IOException e) {
|
||||
throw new BusinessException("写入 Elasticsearch 失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> existingKeys(String holder, Collection<String> keys) {
|
||||
Set<String> found = new HashSet<>();
|
||||
if (keys == null || keys.isEmpty()) {
|
||||
return found;
|
||||
}
|
||||
ensureIndex(holder);
|
||||
try {
|
||||
MgetResponse<BookDocument> response = client.mget(m -> m.index(index(holder)).ids(new ArrayList<>(keys)), BookDocument.class);
|
||||
for (MultiGetResponseItem<BookDocument> item : response.docs()) {
|
||||
if (item.isResult() && item.result().found()) {
|
||||
found.add(item.result().id());
|
||||
}
|
||||
}
|
||||
return found;
|
||||
} catch (IOException e) {
|
||||
throw new BusinessException("读取 Elasticsearch 失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookDocument> findMissing(String sourceHolder, String targetHolder, int limit) {
|
||||
ensureIndex(sourceHolder);
|
||||
ensureIndex(targetHolder);
|
||||
List<BookDocument> missing = new ArrayList<>();
|
||||
List<FieldValue> searchAfter = null;
|
||||
try {
|
||||
while (missing.size() < limit) {
|
||||
List<FieldValue> after = searchAfter;
|
||||
SearchResponse<BookDocument> response = client.search(s -> {
|
||||
s.index(index(sourceHolder)).size(limit).sort(o -> o.field(f -> f.field("_doc").order(SortOrder.Asc)));
|
||||
if (after != null) {
|
||||
s.searchAfter(after);
|
||||
}
|
||||
return s;
|
||||
}, BookDocument.class);
|
||||
List<Hit<BookDocument>> hits = response.hits().hits();
|
||||
if (hits.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
List<String> ids = new ArrayList<>();
|
||||
for (Hit<BookDocument> hit : hits) {
|
||||
ids.add(hit.id());
|
||||
}
|
||||
Set<String> held = existingKeys(targetHolder, ids);
|
||||
for (Hit<BookDocument> hit : hits) {
|
||||
if (hit.source() != null && !held.contains(hit.id()) && missing.size() < limit) {
|
||||
missing.add(hit.source());
|
||||
}
|
||||
}
|
||||
searchAfter = hits.get(hits.size() - 1).sort();
|
||||
if (hits.size() < limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return missing;
|
||||
} catch (IOException e) {
|
||||
throw new BusinessException("读取 Elasticsearch 失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookDocument> findAll(String holder, int limit) {
|
||||
ensureIndex(holder);
|
||||
try {
|
||||
SearchResponse<BookDocument> response = client.search(s -> s.index(index(holder)).size(limit), BookDocument.class);
|
||||
List<BookDocument> books = new ArrayList<>();
|
||||
for (Hit<BookDocument> hit : response.hits().hits()) {
|
||||
if (hit.source() != null) {
|
||||
books.add(hit.source());
|
||||
}
|
||||
}
|
||||
return books;
|
||||
} catch (IOException e) {
|
||||
throw new BusinessException("读取 Elasticsearch 失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureIndex(String holder) {
|
||||
String name = index(holder);
|
||||
try {
|
||||
boolean exists = client.indices().exists(e -> e.index(name)).value();
|
||||
if (!exists) {
|
||||
client.indices().create(c -> c.index(name));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new BusinessException("Elasticsearch 索引不可用:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** 总库和各节点回传箱用不同索引后缀,避免汇总数据和节点收件混在一起。 */
|
||||
private String index(String holder) {
|
||||
String base = properties.getEsIndex();
|
||||
if (holder == null || "CENTER".equalsIgnoreCase(holder)) {
|
||||
return base;
|
||||
}
|
||||
return base + "_" + holder.toLowerCase();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void close() throws IOException {
|
||||
restClient.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.banben.modules.synchub.store;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.banben.common.BusinessException;
|
||||
import com.banben.modules.synchub.model.BookDocument;
|
||||
import com.banben.modules.synchub.service.BookCleaner;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 本机没有 Elasticsearch 时,用业务库里的独立表暂存。不写入 version_resource。
|
||||
* 重复图书按比对键跳过,不覆盖已有记录。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(name = "sync-hub.store", havingValue = "jdbc")
|
||||
public class JdbcBookStore implements BookStore {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final BookCleaner cleaner;
|
||||
|
||||
@Override
|
||||
public int saveNew(String holder, List<BookDocument> books) {
|
||||
String sql = "INSERT INTO sync_hub_book (holder, doc_id, match_key, node_code, source_db, process_no, title, media_type, payload, update_time) "
|
||||
+ "VALUES (?,?,?,?,?,?,?,?,?, CURRENT_TIMESTAMP) "
|
||||
+ "ON CONFLICT (holder, doc_id) DO NOTHING";
|
||||
int inserted = 0;
|
||||
for (BookDocument book : books) {
|
||||
String key = cleaner.matchKey(book);
|
||||
inserted += jdbcTemplate.update(sql, holder, key, key, book.getNodeCode(), book.getSourceDb(),
|
||||
book.getProcessNo(), book.getTitle(), book.getMediaType(), toJson(book));
|
||||
}
|
||||
return inserted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> existingKeys(String holder, Collection<String> keys) {
|
||||
Set<String> found = new HashSet<>();
|
||||
if (keys == null || keys.isEmpty()) {
|
||||
return found;
|
||||
}
|
||||
List<String> list = new ArrayList<>(new LinkedHashSet<>(keys));
|
||||
for (int from = 0; from < list.size(); from += 200) {
|
||||
List<String> part = list.subList(from, Math.min(from + 200, list.size()));
|
||||
StringBuilder marks = new StringBuilder();
|
||||
Object[] args = new Object[part.size() + 1];
|
||||
args[0] = holder;
|
||||
for (int i = 0; i < part.size(); i++) {
|
||||
if (i > 0) {
|
||||
marks.append(',');
|
||||
}
|
||||
marks.append('?');
|
||||
args[i + 1] = part.get(i);
|
||||
}
|
||||
found.addAll(jdbcTemplate.query(
|
||||
"SELECT match_key FROM sync_hub_book WHERE holder = ? AND match_key IN (" + marks + ")",
|
||||
(rs, rowNum) -> rs.getString(1),
|
||||
args));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookDocument> findMissing(String sourceHolder, String targetHolder, int limit) {
|
||||
return jdbcTemplate.query(
|
||||
"SELECT c.payload FROM sync_hub_book c "
|
||||
+ "WHERE c.holder = ? AND c.match_key IS NOT NULL AND NOT EXISTS ("
|
||||
+ "SELECT 1 FROM sync_hub_book n WHERE n.holder = ? AND n.match_key = c.match_key) "
|
||||
+ "ORDER BY c.id LIMIT ?",
|
||||
(rs, rowNum) -> fromJson(rs.getString(1)),
|
||||
sourceHolder, targetHolder, limit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookDocument> findAll(String holder, int limit) {
|
||||
return jdbcTemplate.query(
|
||||
"SELECT payload FROM sync_hub_book WHERE holder = ? ORDER BY id LIMIT ?",
|
||||
(rs, rowNum) -> fromJson(rs.getString(1)),
|
||||
holder, limit);
|
||||
}
|
||||
|
||||
private String toJson(BookDocument book) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(book);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new BusinessException("图书数据无法序列化");
|
||||
}
|
||||
}
|
||||
|
||||
private BookDocument fromJson(String json) {
|
||||
try {
|
||||
return objectMapper.readValue(json, BookDocument.class);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new BusinessException("暂存的图书数据无法读取");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,3 +27,28 @@ spring:
|
||||
logging:
|
||||
level:
|
||||
com.banben: debug
|
||||
|
||||
# 节点与南昌总库的图书同步。本机没有 Elasticsearch,开发期用独立表暂存,不写入 version_resource。
|
||||
# 两台电脑联调时,把 center-url、callback-url 改成对方地址,口令两边保持一致。
|
||||
sync-hub:
|
||||
token: local-mock-hub
|
||||
store: jdbc
|
||||
es-uris: http://127.0.0.1:9200
|
||||
center-url: http://127.0.0.1:8080
|
||||
auto-dispatch: true
|
||||
retry-max: 3
|
||||
batch-size: 200
|
||||
dispatch-limit: 200
|
||||
nodes:
|
||||
- code: NJ_LZ
|
||||
name: 南京陆指
|
||||
kinds: MYSQL
|
||||
callback-url: http://127.0.0.1:8080
|
||||
- code: NJ_LGD
|
||||
name: 南京陆工大
|
||||
kinds: MYSQL,SQLSERVER
|
||||
callback-url: http://127.0.0.1:8080
|
||||
- code: BHF
|
||||
name: 边海防
|
||||
kinds: MOCK
|
||||
callback-url: http://127.0.0.1:8080
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
-- =====================================================================
|
||||
-- 异构数据源同步
|
||||
-- 连接信息、查询 SQL、字段映射全部落库,现场改配置即可,不在代码里写死外部库。
|
||||
-- 兼容 PostgreSQL / 瀚高(HighGo)
|
||||
-- =====================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sync_datasource
|
||||
(
|
||||
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
db_type VARCHAR(32) NOT NULL,
|
||||
host VARCHAR(256) NOT NULL,
|
||||
port INTEGER NOT NULL,
|
||||
db_name VARCHAR(128) NOT NULL,
|
||||
username VARCHAR(128) NOT NULL,
|
||||
password VARCHAR(256),
|
||||
jdbc_params VARCHAR(1000),
|
||||
enabled SMALLINT DEFAULT 1,
|
||||
remark VARCHAR(500),
|
||||
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted SMALLINT DEFAULT 0
|
||||
);
|
||||
|
||||
COMMENT ON TABLE sync_datasource IS '外部数据源连接配置';
|
||||
COMMENT ON COLUMN sync_datasource.db_type IS 'MYSQL / ORACLE / SQLSERVER / POSTGRESQL / HIGHGO';
|
||||
COMMENT ON COLUMN sync_datasource.db_name IS '库名。Oracle 填服务名';
|
||||
COMMENT ON COLUMN sync_datasource.jdbc_params IS '附加连接参数,如 useSSL=false。空则使用该类型的默认参数';
|
||||
COMMENT ON COLUMN sync_datasource.password IS '连接密码,接口不回传';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sync_task
|
||||
(
|
||||
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
datasource_id BIGINT NOT NULL,
|
||||
query_sql TEXT NOT NULL,
|
||||
target_table VARCHAR(64) NOT NULL DEFAULT 'version_resource',
|
||||
batch_size INTEGER DEFAULT 200,
|
||||
retry_times INTEGER DEFAULT 1,
|
||||
cron_expr VARCHAR(64),
|
||||
schedule_enabled SMALLINT DEFAULT 0,
|
||||
sync_mode VARCHAR(16) DEFAULT 'FULL',
|
||||
increment_column VARCHAR(64),
|
||||
increment_value VARCHAR(128),
|
||||
unique_fields VARCHAR(256),
|
||||
enabled SMALLINT DEFAULT 1,
|
||||
last_schedule_time TIMESTAMP,
|
||||
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted SMALLINT DEFAULT 0
|
||||
);
|
||||
|
||||
COMMENT ON TABLE sync_task IS '同步任务:查询 SQL、目标表、批次、重试、定时与增量水位';
|
||||
COMMENT ON COLUMN sync_task.query_sql IS '外部库查询语句,只允许单条 SELECT。增量可写占位符 ${watermark}';
|
||||
COMMENT ON COLUMN sync_task.sync_mode IS 'FULL 全量 / INCREMENT 增量(增量需在 SQL 中使用 ${watermark})';
|
||||
COMMENT ON COLUMN sync_task.increment_column IS '增量水位来源列,成功后取本批最大值写回 increment_value';
|
||||
COMMENT ON COLUMN sync_task.increment_value IS '上次成功同步的水位,增量预留';
|
||||
COMMENT ON COLUMN sync_task.unique_fields IS '去重字段,目标表列名,多个用英文逗号分隔';
|
||||
COMMENT ON COLUMN sync_task.cron_expr IS 'Spring 6 位 cron:秒 分 时 日 月 周';
|
||||
COMMENT ON COLUMN sync_task.last_schedule_time IS '上次定时触发时间,用于计算下一次 cron';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sync_field_map
|
||||
(
|
||||
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||
task_id BIGINT NOT NULL,
|
||||
source_field VARCHAR(128) NOT NULL,
|
||||
target_field VARCHAR(64) NOT NULL,
|
||||
data_type VARCHAR(16) DEFAULT 'STRING',
|
||||
clean_rule VARCHAR(32) DEFAULT 'TRIM',
|
||||
required_flag SMALLINT DEFAULT 0,
|
||||
default_value VARCHAR(256),
|
||||
sort_no INTEGER DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sync_field_task ON sync_field_map (task_id);
|
||||
|
||||
COMMENT ON TABLE sync_field_map IS '外部字段到目标表字段的映射,随任务保存,不写死在代码中';
|
||||
COMMENT ON COLUMN sync_field_map.data_type IS 'STRING / INTEGER / LONG / DECIMAL / DATE / DATETIME';
|
||||
COMMENT ON COLUMN sync_field_map.clean_rule IS 'NONE / TRIM / UPPER / LOWER / DIGITS / COMPACT_DATE';
|
||||
COMMENT ON COLUMN sync_field_map.default_value IS '源值为空时使用。可用 ${uuid} ${today} ${year} ${seq} ${task}';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sync_log
|
||||
(
|
||||
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||
task_id BIGINT,
|
||||
datasource_id BIGINT,
|
||||
task_name VARCHAR(128),
|
||||
datasource_name VARCHAR(128),
|
||||
trigger_type VARCHAR(16),
|
||||
status VARCHAR(16),
|
||||
start_time TIMESTAMP,
|
||||
end_time TIMESTAMP,
|
||||
success_count INTEGER DEFAULT 0,
|
||||
fail_count INTEGER DEFAULT 0,
|
||||
skip_count INTEGER DEFAULT 0,
|
||||
error_message TEXT,
|
||||
detail TEXT,
|
||||
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sync_log_task ON sync_log (task_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_sync_log_start ON sync_log (start_time);
|
||||
|
||||
COMMENT ON TABLE sync_log IS '每一次同步的执行记录';
|
||||
COMMENT ON COLUMN sync_log.trigger_type IS 'MANUAL 手动 / SCHEDULE 定时';
|
||||
COMMENT ON COLUMN sync_log.status IS 'RUNNING / SUCCESS / PARTIAL / FAILED';
|
||||
COMMENT ON COLUMN sync_log.skip_count IS '因去重跳过的条数';
|
||||
@@ -0,0 +1,51 @@
|
||||
-- 节点与南昌总库的图书同步记录。不改 version_resource。
|
||||
-- 兼容 PostgreSQL / 瀚高
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sync_hub_record
|
||||
(
|
||||
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||
task_no VARCHAR(64) NOT NULL,
|
||||
direction VARCHAR(8) NOT NULL,
|
||||
source_node VARCHAR(32),
|
||||
target_node VARCHAR(32),
|
||||
source_db VARCHAR(32),
|
||||
book_count INTEGER DEFAULT 0,
|
||||
skip_count INTEGER DEFAULT 0,
|
||||
status VARCHAR(16) NOT NULL,
|
||||
error_message VARCHAR(1000),
|
||||
retry_count INTEGER DEFAULT 0,
|
||||
max_retry INTEGER DEFAULT 3,
|
||||
start_time TIMESTAMP,
|
||||
end_time TIMESTAMP,
|
||||
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sync_hub_record_status ON sync_hub_record (status, create_time);
|
||||
|
||||
COMMENT ON TABLE sync_hub_record IS '图书同步记录:上推 UP、回传 DOWN';
|
||||
COMMENT ON COLUMN sync_hub_record.direction IS 'UP 节点推总库 / DOWN 总库回传节点';
|
||||
COMMENT ON COLUMN sync_hub_record.status IS 'RUNNING / SUCCESS / FAILED';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sync_hub_book
|
||||
(
|
||||
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||
holder VARCHAR(32) NOT NULL,
|
||||
doc_id VARCHAR(320) NOT NULL,
|
||||
match_key VARCHAR(320),
|
||||
node_code VARCHAR(32),
|
||||
source_db VARCHAR(32),
|
||||
process_no VARCHAR(128),
|
||||
title VARCHAR(512),
|
||||
media_type VARCHAR(32),
|
||||
payload TEXT NOT NULL,
|
||||
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_sync_hub_book ON sync_hub_book (holder, doc_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_sync_hub_book_match ON sync_hub_book (holder, match_key);
|
||||
|
||||
COMMENT ON TABLE sync_hub_book IS '总库或节点暂存的图书元数据。store=es 时总库改写入 Elasticsearch';
|
||||
COMMENT ON COLUMN sync_hub_book.holder IS 'CENTER 表示总库,节点编码表示该节点收到的回传';
|
||||
COMMENT ON COLUMN sync_hub_book.match_key IS '比对键。有 ISBN 用 ISBN,否则用题名、作者、出版年';
|
||||
COMMENT ON COLUMN sync_hub_record.skip_count IS '比对后已存在、未写入的条数';
|
||||
COMMENT ON COLUMN sync_hub_record.book_count IS '本次新写入的条数';
|
||||
Reference in New Issue
Block a user