页面优化 数据采集

This commit is contained in:
lmy
2026-10-23 15:16:27 +08:00
parent a68f27f7f2
commit 20660da286
13 changed files with 425 additions and 88 deletions
@@ -30,6 +30,20 @@ public class CollectController {
return Result.success(collectService.createTask(task));
}
@Operation(summary = "修改采集任务")
@PutMapping("/task/{id}")
public Result<Void> updateTask(@PathVariable Long id, @RequestBody CollectTask task) {
collectService.updateTask(id, task);
return Result.success();
}
@Operation(summary = "删除采集任务")
@DeleteMapping("/task/{id}")
public Result<Void> removeTask(@PathVariable Long id) {
collectService.removeTask(id);
return Result.success();
}
@Operation(summary = "测试来源库连接,并查看表字段如何写入版本资源表")
@PostMapping("/preview")
public Result<CollectTableVO> preview(@RequestBody CollectTask source) {
@@ -0,0 +1,27 @@
package com.banben.modules.collect.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 版本资源表字段与来源列的对照。
*/
@Data
@Schema(description = "版本资源字段对照")
public class CollectFieldCompareVO {
@Schema(description = "version_resource 字段名")
private String targetField;
@Schema(description = "字段中文名")
private String targetLabel;
@Schema(description = "是否为必备字段")
private boolean required;
@Schema(description = "对应的来源列名,没有则为空")
private String sourceColumn;
@Schema(description = "来源表是否有列对应到该字段")
private boolean matched;
}
@@ -21,4 +21,7 @@ public class CollectTableVO {
@Schema(description = "列与版本资源字段的对应关系")
private List<CollectColumnVO> columns = new ArrayList<>();
@Schema(description = "版本资源表字段与来源列的对照")
private List<CollectFieldCompareVO> compares = new ArrayList<>();
}
@@ -36,7 +36,10 @@ public class CollectTask implements Serializable {
@Schema(description = "数据库地址,如 10.1.1.14")
private String dbHost;
@Schema(description = "数据库端口,瀚高默认 5866,PostgreSQL 默认 5432")
@Schema(description = "来源数据库类型:MYSQL 或 POSTGRESQL(瀚高走 PostgreSQL 协议)")
private String dbType;
@Schema(description = "数据库端口。MySQL 常用 3306,PostgreSQL 常用 5432,瀚高常用 5866")
private Integer dbPort;
@Schema(description = "数据库名")
@@ -16,6 +16,16 @@ public interface CollectService extends IService<CollectTask> {
*/
Long createTask(CollectTask task);
/**
* 修改采集任务的连接信息。密码留空则保持原密码。
*/
void updateTask(Long id, CollectTask task);
/**
* 删除采集任务。
*/
void removeTask(Long id);
/**
* 执行采集任务,返回执行后的任务(含采集条数和结果说明)。
*/
@@ -50,7 +50,7 @@ public class CollectServiceImpl extends ServiceImpl<CollectTaskMapper, CollectTa
.collect(Collectors.toMap(c -> c.sourceType().toUpperCase(), Function.identity(), (a, b) -> a));
}
/** 创建任务:初始状态 PENDING、已采集量 0,目标量缺省为 20 万条。 */
/** 创建任务:初始状态 PENDING、已采集量 0。来源表至少要有一列能写入版本资源表。 */
@Override
public Long createTask(CollectTask task) {
task.setId(null);
@@ -59,15 +59,78 @@ public class CollectServiceImpl extends ServiceImpl<CollectTaskMapper, CollectTa
if (task.getTargetCount() == null) {
task.setTargetCount(200000);
}
ensureMapped(task);
this.save(task);
return task.getId();
}
@Override
public void updateTask(Long id, CollectTask task) {
CollectTask stored = requireTask(id);
if ("RUNNING".equals(stored.getStatus())) {
throw new BusinessException("任务正在执行,不能修改");
}
stored.setLibraryCode(task.getLibraryCode());
stored.setLibraryName(task.getLibraryName());
stored.setSourceType(task.getSourceType() == null ? "DB" : task.getSourceType());
stored.setDbHost(task.getDbHost());
stored.setDbType(task.getDbType());
stored.setDbPort(task.getDbPort());
stored.setDbName(task.getDbName());
stored.setDbUsername(task.getDbUsername());
stored.setSourceTable(task.getSourceTable());
if (task.getDbPassword() != null && !task.getDbPassword().isBlank()) {
stored.setDbPassword(task.getDbPassword());
}
ensureMapped(stored);
this.updateById(stored);
}
@Override
public void removeTask(Long id) {
CollectTask stored = requireTask(id);
if ("RUNNING".equals(stored.getStatus())) {
throw new BusinessException("任务正在执行,不能删除");
}
this.removeById(id);
}
@Override
public CollectTableVO previewSource(CollectTask source) {
fillPassword(source);
return dbTableCollector.preview(source);
}
private CollectTask requireTask(Long id) {
CollectTask stored = this.getById(id);
if (stored == null) {
throw new BusinessException("采集任务不存在");
}
return stored;
}
/** 编辑时密码留空,沿用已保存的密码再去测试连接。 */
private void fillPassword(CollectTask source) {
if (source.getDbPassword() != null && !source.getDbPassword().isBlank()) {
return;
}
if (source.getId() == null) {
return;
}
CollectTask stored = this.getById(source.getId());
if (stored != null) {
source.setDbPassword(stored.getDbPassword());
}
}
private void ensureMapped(CollectTask task) {
CollectTableVO preview = previewSource(task);
boolean matched = preview.getColumns().stream().anyMatch(column -> column.getTargetField() != null);
if (!matched) {
throw new BusinessException("来源表至少要有一列能对应到版本资源表");
}
}
@Override
public CollectTask startTask(Long taskId) {
CollectTask task = this.getById(taskId);
@@ -3,6 +3,7 @@ package com.banben.modules.collect.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.common.BusinessException;
import com.banben.modules.collect.dto.CollectColumnVO;
import com.banben.modules.collect.dto.CollectFieldCompareVO;
import com.banben.modules.collect.dto.CollectTableVO;
import com.banben.modules.collect.entity.CollectTask;
import com.banben.modules.collect.service.Collector;
@@ -44,6 +45,12 @@ public class DbTableCollector implements Collector {
private static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("yyyyMMdd");
private static final int MAX_ROWS = 200000;
/** 写入 version_resource 时建议具备的字段。正题名未对应则该行无法入库。 */
private static final List<String> REQUIRED_FIELDS = List.of(
"title", "processNo", "clcCode", "keywords", "summary", "publishYear", "processDate",
"contentForm", "mediaType", "format", "language", "fulltextUrl"
);
private static final Map<String, String> FIELD_BY_COLUMN = new HashMap<>();
private static final Map<String, String> FIELD_LABEL = new LinkedHashMap<>();
private static final Map<String, BiConsumer<VersionResource, String>> SETTERS = new HashMap<>();
@@ -151,13 +158,14 @@ public class DbTableCollector implements Collector {
* 用页面填写的地址、账号和表名连接来源库,返回行数以及列如何写入版本资源表。
*/
public CollectTableVO preview(CollectTask task) {
String[] qualified = qualify(task.getSourceTable());
String[] qualified = qualify(task);
try (Connection connection = openConnection(task)) {
ensureTable(connection, qualified[0], qualified[1]);
qualified[1] = canonicalTable(connection, qualified[0], qualified[1], mysql(task));
CollectTableVO table = new CollectTableVO();
table.setTableName(qualified[0] + "." + qualified[1]);
table.setRowCount(countRows(connection, qualified[0], qualified[1]));
table.setRowCount(countRows(connection, qualified[0], qualified[1], mysql(task)));
table.setColumns(readColumns(connection, qualified[0], qualified[1]));
table.setCompares(buildCompares(table.getColumns()));
return table;
} catch (SQLException e) {
throw new BusinessException(sqlMessage(e));
@@ -166,12 +174,16 @@ public class DbTableCollector implements Collector {
@Override
public int collect(CollectTask task) {
String[] qualified = qualify(task.getSourceTable());
String[] qualified = qualify(task);
int limit = task.getTargetCount() == null ? MAX_ROWS : Math.min(Math.max(task.getTargetCount(), 1), MAX_ROWS);
List<Map<String, Object>> rows;
try (Connection connection = openConnection(task)) {
ensureTable(connection, qualified[0], qualified[1]);
rows = readRows(connection, qualified[0], qualified[1], limit);
qualified[1] = canonicalTable(connection, qualified[0], qualified[1], mysql(task));
List<CollectColumnVO> columns = readColumns(connection, qualified[0], qualified[1]);
if (columns.stream().noneMatch(column -> column.getTargetField() != null)) {
throw new BusinessException("来源表至少要有一列能对应到版本资源表,无法写入");
}
rows = readRows(connection, qualified[0], qualified[1], limit, mysql(task));
} catch (SQLException e) {
throw new BusinessException(sqlMessage(e));
}
@@ -260,7 +272,11 @@ public class DbTableCollector implements Collector {
if (blank(task.getDbPassword())) {
throw new BusinessException("请填写数据库密码");
}
String url = "jdbc:postgresql://" + task.getDbHost().trim() + ":" + port + "/"
String url = mysql(task)
? "jdbc:mysql://" + task.getDbHost().trim() + ":" + port + "/" + task.getDbName().trim()
+ "?connectTimeout=8000&socketTimeout=30000&useSSL=false&allowPublicKeyRetrieval=true"
+ "&characterEncoding=utf8&serverTimezone=Asia/Shanghai"
: "jdbc:postgresql://" + task.getDbHost().trim() + ":" + port + "/"
+ task.getDbName().trim() + "?connectTimeout=8&socketTimeout=30";
Properties properties = new Properties();
properties.setProperty("user", task.getDbUsername().trim());
@@ -272,47 +288,87 @@ public class DbTableCollector implements Collector {
}
}
private String[] qualify(String raw) {
if (blank(raw)) {
/**
* 按页面选择的数据库类型决定驱动。未填写类型的旧任务仍按 3306 识别为 MySQL。
*/
private boolean mysql(CollectTask task) {
String type = task.getDbType() == null ? "" : task.getDbType().trim().toUpperCase(Locale.ROOT);
if ("MYSQL".equals(type)) {
return true;
}
if ("POSTGRESQL".equals(type) || "HIGHGO".equals(type)) {
return false;
}
if (type.isEmpty()) {
return task.getDbPort() != null && task.getDbPort() == 3306;
}
throw new BusinessException("数据库类型只支持 MySQL 或 PostgreSQL");
}
private String[] qualify(CollectTask task) {
if (blank(task.getSourceTable())) {
throw new BusinessException("请填写要采集的表名");
}
String[] parts = raw.trim().split("\\.");
String[] parts = task.getSourceTable().trim().split("\\.");
if (parts.length > 2) {
throw new BusinessException("表名格式应为表名,或模式名.表名");
}
String schema = parts.length == 2 ? parts[0] : "public";
boolean mysql = mysql(task);
String schema = parts.length == 2 ? parts[0] : (mysql ? task.getDbName().trim() : "public");
String table = parts.length == 2 ? parts[1] : parts[0];
if (!schema.matches("[A-Za-z_][A-Za-z0-9_]*") || !table.matches("[A-Za-z_][A-Za-z0-9_]*")) {
throw new BusinessException("表名只能包含字母、数字和下划线");
}
return new String[]{schema.toLowerCase(Locale.ROOT), table.toLowerCase(Locale.ROOT)};
if (!mysql) {
schema = schema.toLowerCase(Locale.ROOT);
table = table.toLowerCase(Locale.ROOT);
}
return new String[]{schema, table};
}
private void ensureTable(Connection connection, String schema, String table) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement("""
SELECT COUNT(*) FROM information_schema.tables
private String canonicalTable(Connection connection, String schema, String table, boolean mysql) throws SQLException {
String sql = mysql
? """
SELECT table_name FROM information_schema.tables
WHERE table_schema = ? AND LOWER(table_name) = LOWER(?)
"""
: """
SELECT table_name FROM information_schema.tables
WHERE table_schema = ? AND table_name = ?
""")) {
""";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, schema);
statement.setString(2, table);
try (ResultSet resultSet = statement.executeQuery()) {
resultSet.next();
if (resultSet.getInt(1) == 0) {
String found = null;
while (resultSet.next()) {
String name = resultSet.getString(1);
if (name.equals(table)) {
return name;
}
found = name;
}
if (found == null) {
throw new BusinessException("来源库中不存在表:" + schema + "." + table);
}
return found;
}
}
}
private long countRows(Connection connection, String schema, String table) throws SQLException {
private long countRows(Connection connection, String schema, String table, boolean mysql) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(
"SELECT COUNT(*) FROM \"" + schema + "\".\"" + table + "\"");
"SELECT COUNT(*) FROM " + quote(schema, mysql) + "." + quote(table, mysql));
ResultSet resultSet = statement.executeQuery()) {
resultSet.next();
return resultSet.getLong(1);
}
}
private String quote(String identifier, boolean mysql) {
return mysql ? "`" + identifier + "`" : "\"" + identifier + "\"";
}
private List<CollectColumnVO> readColumns(Connection connection, String schema, String table) throws SQLException {
List<CollectColumnVO> columns = new ArrayList<>();
try (PreparedStatement statement = connection.prepareStatement("""
@@ -337,11 +393,11 @@ public class DbTableCollector implements Collector {
return columns;
}
private List<Map<String, Object>> readRows(Connection connection, String schema, String table, int limit)
throws SQLException {
private List<Map<String, Object>> readRows(Connection connection, String schema, String table, int limit,
boolean mysql) throws SQLException {
List<Map<String, Object>> rows = new ArrayList<>();
try (PreparedStatement statement = connection.prepareStatement(
"SELECT * FROM \"" + schema + "\".\"" + table + "\" LIMIT " + limit);
"SELECT * FROM " + quote(schema, mysql) + "." + quote(table, mysql) + " LIMIT " + limit);
ResultSet resultSet = statement.executeQuery()) {
ResultSetMetaData meta = resultSet.getMetaData();
while (resultSet.next()) {
@@ -358,13 +414,14 @@ public class DbTableCollector implements Collector {
private String sqlMessage(SQLException exception) {
String message = exception.getMessage() == null ? "" : exception.getMessage();
String lower = message.toLowerCase(Locale.ROOT);
if (lower.contains("password authentication failed") || lower.contains("authentication failed")) {
if (lower.contains("password authentication failed") || lower.contains("authentication failed")
|| lower.contains("access denied")) {
return "数据库用户名或密码错误";
}
if (lower.contains("does not exist") && lower.contains("database")) {
if ((lower.contains("does not exist") && lower.contains("database")) || lower.contains("unknown database")) {
return "数据库不存在";
}
if (lower.contains("connection refused")) {
if (lower.contains("connection refused") || lower.contains("communications link failure")) {
return "连接被拒绝,请检查数据库地址和端口";
}
if (lower.contains("timeout") || lower.contains("timed out")) {
@@ -377,6 +434,37 @@ public class DbTableCollector implements Collector {
return brief.isEmpty() ? "连接数据库失败" : "连接数据库失败:" + brief;
}
private List<CollectFieldCompareVO> buildCompares(List<CollectColumnVO> columns) {
Map<String, String> sourceByField = new LinkedHashMap<>();
for (CollectColumnVO column : columns) {
if (column.getTargetField() != null) {
sourceByField.putIfAbsent(column.getTargetField(), column.getColumnName());
}
}
List<CollectFieldCompareVO> compares = new ArrayList<>();
Set<String> seen = new HashSet<>();
for (String field : REQUIRED_FIELDS) {
compares.add(compareItem(field, true, sourceByField));
seen.add(field);
}
for (String field : FIELD_LABEL.keySet()) {
if (!seen.contains(field)) {
compares.add(compareItem(field, false, sourceByField));
}
}
return compares;
}
private CollectFieldCompareVO compareItem(String field, boolean required, Map<String, String> sourceByField) {
CollectFieldCompareVO item = new CollectFieldCompareVO();
item.setTargetField(field);
item.setTargetLabel(FIELD_LABEL.get(field));
item.setRequired(required);
item.setSourceColumn(sourceByField.get(field));
item.setMatched(item.getSourceColumn() != null);
return item;
}
private Set<String> loadProcessNos() {
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.select(VersionResource::getProcessNo).isNotNull(VersionResource::getProcessNo);
@@ -18,7 +18,7 @@ import java.util.List;
/**
* 数据治理接口。
*
* <p>对应「数据治理」四动作:聚同、优化、提示、提纯。</p>
* <p>对应「数据治理」:聚同、优化、提示、提纯。</p>
* <ul>
* <li>优化:整合聚同文献的不同描述元数据,生成质量更高、要素更完整的元数据。</li>
* <li>提示:生成疑似同一文献提示清单、疑似元数据错漏提示清单。</li>
@@ -0,0 +1,4 @@
-- 采集任务记录来源库类型,连接时按类型选择驱动。
ALTER TABLE collect_task ADD COLUMN IF NOT EXISTS db_type VARCHAR(32);
COMMENT ON COLUMN collect_task.db_type IS '来源数据库类型:MYSQL 或 POSTGRESQL';
@@ -53,6 +53,7 @@ CREATE TABLE IF NOT EXISTS collect_task
library_name VARCHAR(256), -- 单位名称
source_type VARCHAR(64), -- 数据源类型:MARC/EXCEL/DB/API
db_host VARCHAR(256), -- 来源库地址
db_type VARCHAR(32), -- 来源库类型:MYSQL / POSTGRESQL
db_port INTEGER, -- 来源库端口
db_name VARCHAR(128), -- 来源库名
db_username VARCHAR(128), -- 来源库用户名