Compare commits

..

24 Commits

Author SHA1 Message Date
lmy eb985706c4 推送数据 2026-11-13 16:19:23 +08:00
lmy 37566e9d7e 推送数据 2026-11-13 14:29:03 +08:00
zhaichao f1765c039c 版本资源综合比例 2026-11-04 16:00:07 +08:00
zhaichao 7794716861 二次检索 2026-11-04 15:45:19 +08:00
zhaichao 3d2a3e7766 用户访问数量 2026-11-04 15:28:32 +08:00
zhaichao 5cf7b35a58 日志统计 2026-11-04 15:26:24 +08:00
zhaichao 7438f558e2 日志 2026-11-04 14:50:25 +08:00
zhaichao 0b5c0a40e9 日志 2026-11-04 14:39:25 +08:00
zhaichao 4f3fc578d0 中图法分类 2026-11-04 14:08:14 +08:00
zhaichao 0d8fdbd35a 支持统计筛选 2026-11-04 13:45:57 +08:00
liweijie b76a7ccce4 角色默认为USER 2026-10-30 15:51:10 +08:00
liweijie f4f24398ee 添加对于用户的组织、角色分配 2026-10-30 15:43:03 +08:00
zhaichao 8546afa24e feat: 新增版本资源 32 著录字段数据库迁移脚本(幂等) 2026-10-30 15:29:34 +08:00
zhaichao 3dca829cf3 新增校验 2026-10-30 15:25:03 +08:00
zhaichao a2ea2389e5 Revert "补全字段"
This reverts commit 8bdaafb69b.
2026-10-30 15:01:50 +08:00
zhaichao 8bdaafb69b 补全字段 2026-10-30 14:56:35 +08:00
liweijie 28fd91e46e 1、sql输出调整,否则会占满资源;
2、添加组织角色管理模块;
3、后台管理样式调整,改为左侧边栏
2026-10-30 14:45:39 +08:00
zhaichao f1e68697b5 搜索去除关键字 2026-10-30 14:04:05 +08:00
zhaichao 3a0705692a 馆藏轮播图有封面优先展示封面 2026-10-30 11:25:30 +08:00
zhaichao f02323e350 馆藏轮播图样式调整 2026-10-30 11:23:16 +08:00
zhaichao 7024ad09ac 小字tag移除 2026-10-30 11:20:47 +08:00
zhaichao 4e5eb6ca5b 标题修改 2026-10-30 11:18:29 +08:00
yangbin b24c5e3849 Merge remote-tracking branch 'origin/master' 2026-10-29 09:16:24 +08:00
yangbin 4990a48b2c 元数据模板导出 excel导入 5000条上限取消 2026-10-29 09:16:18 +08:00
122 changed files with 10946 additions and 169 deletions
+18
View File
@@ -68,6 +68,24 @@
<artifactId>mysql-connector-j</artifactId> <artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </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> <dependency>
@@ -1,6 +1,9 @@
package com.banben.config; package com.banben.config;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.modules.admin.entity.SysRole;
import com.banben.modules.admin.mapper.SysRoleMapper;
import com.banben.modules.admin.service.RoleService;
import com.banben.modules.auth.entity.SysUser; import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper; import com.banben.modules.auth.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -21,17 +24,18 @@ import org.springframework.stereotype.Component;
public class DataInitializer implements ApplicationRunner { public class DataInitializer implements ApplicationRunner {
private final SysUserMapper sysUserMapper; private final SysUserMapper sysUserMapper;
private final SysRoleMapper sysRoleMapper;
private final RoleService roleService;
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
@Override @Override
public void run(ApplicationArguments args) { public void run(ApplicationArguments args) {
ensureRoles();
try { try {
LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysUser::getUsername, "admin"); wrapper.eq(SysUser::getUsername, "admin");
Long count = sysUserMapper.selectCount(wrapper); Long count = sysUserMapper.selectCount(wrapper);
if (count != null && count > 0) { if (count == null || count == 0) {
return;
}
SysUser admin = new SysUser(); SysUser admin = new SysUser();
admin.setUsername("admin"); admin.setUsername("admin");
admin.setPassword(passwordEncoder.encode("admin123")); admin.setPassword(passwordEncoder.encode("admin123"));
@@ -41,8 +45,35 @@ public class DataInitializer implements ApplicationRunner {
admin.setStatus(1); admin.setStatus(1);
sysUserMapper.insert(admin); sysUserMapper.insert(admin);
log.info("已创建默认管理员账号:admin / admin123"); log.info("已创建默认管理员账号:admin / admin123");
}
} catch (Exception e) { } catch (Exception e) {
log.warn("初始化默认管理员失败(可能表未创建):{}", e.getMessage()); log.warn("初始化默认管理员失败(可能表未创建):{}", e.getMessage());
} }
bindAdminRole();
}
private void ensureRoles() {
try {
roleService.ensureBuiltin();
} catch (Exception e) {
log.warn("初始化内置角色失败(可能表未创建):{}", e.getMessage());
}
}
private void bindAdminRole() {
try {
SysRole adminRole = sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, "ADMIN"));
if (adminRole == null) {
return;
}
SysUser admin = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, "admin"));
if (admin != null && admin.getRoleId() == null) {
admin.setRoleId(adminRole.getId());
admin.setRole("ADMIN");
sysUserMapper.updateById(admin);
}
} catch (Exception e) {
log.warn("回填管理员角色失败:{}", e.getMessage());
}
} }
} }
@@ -0,0 +1,47 @@
package com.banben.config;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.format.DateTimeFormatter;
/**
* 统一 java.time 类型的 JSON 序列化格式。
*
* <p>Spring 的 {@code spring.jackson.date-format} 只作用于 {@code java.util.Date},
* 对 {@code LocalDateTime/LocalDate/LocalTime} 默认序列化为带 T 的 ISO-8601(如 2026-11-04T10:30:00),
* 前端展示与解析都不友好。这里统一改为可读格式:</p>
* <ul>
* <li>LocalDateTime → yyyy-MM-dd HH:mm:ss</li>
* <li>LocalDate → yyyy-MM-dd</li>
* <li>LocalTime → HH:mm:ss</li>
* </ul>
*/
@Configuration
public class JacksonConfig {
private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static final String DATE_PATTERN = "yyyy-MM-dd";
private static final String TIME_PATTERN = "HH:mm:ss";
@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
DateTimeFormatter df = DateTimeFormatter.ofPattern(DATE_PATTERN);
DateTimeFormatter tf = DateTimeFormatter.ofPattern(TIME_PATTERN);
return builder -> builder
.serializerByType(java.time.LocalDateTime.class, new LocalDateTimeSerializer(dtf))
.serializerByType(java.time.LocalDate.class, new LocalDateSerializer(df))
.serializerByType(java.time.LocalTime.class, new LocalTimeSerializer(tf))
.deserializerByType(java.time.LocalDateTime.class, new LocalDateTimeDeserializer(dtf))
.deserializerByType(java.time.LocalDate.class, new LocalDateDeserializer(df))
.deserializerByType(java.time.LocalTime.class, new LocalTimeDeserializer(tf));
}
}
@@ -1,6 +1,7 @@
package com.banben.config; package com.banben.config;
import com.banben.modules.auth.interceptor.AuthInterceptor; import com.banben.modules.auth.interceptor.AuthInterceptor;
import com.banben.modules.synchub.config.HubTokenInterceptor;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry; 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 { public class WebMvcConfig implements WebMvcConfigurer {
private final AuthInterceptor authInterceptor; 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 /api/auth/logout} —— 登出由前端清令牌,网络异常时也应能调用</li>
* <li>{@code /swagger-ui/**}、{@code /v3/api-docs/**} —— 接口文档</li> * <li>{@code /swagger-ui/**}、{@code /v3/api-docs/**} —— 接口文档</li>
* <li>{@code /actuator/**} —— 健康检查(容器探针需要)</li> * <li>{@code /actuator/**} —— 健康检查(容器探针需要)</li>
* <li>{@code /api/hub/**} —— 节点与总库互调用同步口令,不用用户登录令牌</li>
* </ul> * </ul>
*/ */
@Override @Override
@@ -58,7 +61,10 @@ public class WebMvcConfig implements WebMvcConfigurer {
"/api/auth/logout", "/api/auth/logout",
"/swagger-ui/**", "/swagger-ui/**",
"/v3/api-docs/**", "/v3/api-docs/**",
"/actuator/**" "/actuator/**",
"/api/hub/**"
); );
registry.addInterceptor(hubTokenInterceptor)
.addPathPatterns("/api/hub/**");
} }
} }
@@ -0,0 +1,65 @@
package com.banben.modules.admin.controller;
import com.banben.common.Result;
import com.banben.modules.admin.dto.OrgSaveRequest;
import com.banben.modules.admin.dto.OrgTreeVO;
import com.banben.modules.admin.service.OrgService;
import com.banben.modules.admin.support.AdminAccess;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
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.RestController;
import java.util.List;
/**
* 多层级组织管理。
*/
@Tag(name = "后台管理-组织")
@RestController
@RequestMapping("/api/admin/orgs")
@RequiredArgsConstructor
public class OrgController {
private final OrgService orgService;
private final AdminAccess adminAccess;
@Operation(summary = "组织树")
@GetMapping("/tree")
public Result<List<OrgTreeVO>> tree() {
adminAccess.require();
return Result.success(orgService.tree());
}
@Operation(summary = "新增组织")
@PostMapping
public Result<Void> create(@Valid @RequestBody OrgSaveRequest request) {
adminAccess.require();
orgService.create(request);
return Result.success();
}
@Operation(summary = "修改组织")
@PutMapping("/{id}")
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody OrgSaveRequest request) {
adminAccess.require();
orgService.update(id, request);
return Result.success();
}
@Operation(summary = "删除组织")
@DeleteMapping("/{id}")
public Result<Void> remove(@PathVariable Long id) {
adminAccess.require();
orgService.remove(id);
return Result.success();
}
}
@@ -0,0 +1,65 @@
package com.banben.modules.admin.controller;
import com.banben.common.Result;
import com.banben.modules.admin.dto.RoleSaveRequest;
import com.banben.modules.admin.entity.SysRole;
import com.banben.modules.admin.service.RoleService;
import com.banben.modules.admin.support.AdminAccess;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
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.RestController;
import java.util.List;
/**
* 角色管理。
*/
@Tag(name = "后台管理-角色")
@RestController
@RequestMapping("/api/admin/roles")
@RequiredArgsConstructor
public class RoleController {
private final RoleService roleService;
private final AdminAccess adminAccess;
@Operation(summary = "角色列表")
@GetMapping
public Result<List<SysRole>> list() {
adminAccess.require();
return Result.success(roleService.listAll());
}
@Operation(summary = "新增角色")
@PostMapping
public Result<Void> create(@Valid @RequestBody RoleSaveRequest request) {
adminAccess.require();
roleService.create(request);
return Result.success();
}
@Operation(summary = "修改角色")
@PutMapping("/{id}")
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody RoleSaveRequest request) {
adminAccess.require();
roleService.update(id, request);
return Result.success();
}
@Operation(summary = "删除角色")
@DeleteMapping("/{id}")
public Result<Void> remove(@PathVariable Long id) {
adminAccess.require();
roleService.remove(id);
return Result.success();
}
}
@@ -0,0 +1,96 @@
package com.banben.modules.admin.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.banben.common.Result;
import com.banben.modules.admin.dto.UserSaveRequest;
import com.banben.modules.admin.dto.UserVO;
import com.banben.modules.admin.service.UserAdminService;
import com.banben.modules.admin.service.UserExcelService;
import com.banben.modules.admin.support.AdminAccess;
import com.banben.modules.resource.dto.ImportResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
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 org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* 用户管理,含导入模板导出和批量导入。
*/
@Tag(name = "后台管理-用户")
@RestController
@RequestMapping("/api/admin/users")
@RequiredArgsConstructor
public class UserAdminController {
private final UserAdminService userAdminService;
private final UserExcelService userExcelService;
private final AdminAccess adminAccess;
@Operation(summary = "分页查询用户")
@GetMapping("/page")
public Result<Page<UserVO>> page(@RequestParam(defaultValue = "1") long current,
@RequestParam(defaultValue = "10") long size,
@RequestParam(required = false) String keyword,
@RequestParam(required = false) Long orgId,
@RequestParam(required = false) Long roleId) {
adminAccess.require();
return Result.success(userAdminService.page(current, size, keyword, orgId, roleId));
}
@Operation(summary = "新增用户")
@PostMapping
public Result<Void> create(@Valid @RequestBody UserSaveRequest request) {
adminAccess.require();
userAdminService.create(request);
return Result.success();
}
@Operation(summary = "修改用户")
@PutMapping("/{id}")
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody UserSaveRequest request) {
adminAccess.require();
userAdminService.update(id, request);
return Result.success();
}
@Operation(summary = "删除用户")
@DeleteMapping("/{id}")
public Result<Void> remove(@PathVariable Long id) {
adminAccess.require();
userAdminService.remove(id);
return Result.success();
}
@Operation(summary = "导出用户导入模板")
@GetMapping("/import-template")
public void template(jakarta.servlet.http.HttpServletResponse response) throws IOException {
adminAccess.require();
String fileName = URLEncoder.encode("用户导入模板.xlsx", StandardCharsets.UTF_8);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition",
"attachment; filename=" + fileName + "; filename*=UTF-8''" + fileName);
userExcelService.writeTemplate(response.getOutputStream());
}
@Operation(summary = "批量导入用户")
@PostMapping("/import")
public Result<ImportResult> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
adminAccess.require();
return Result.success(userExcelService.importExcel(file));
}
}
@@ -0,0 +1,30 @@
package com.banben.modules.admin.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
/**
* 新增或修改组织。
*/
@Data
public class OrgSaveRequest {
/** 上级组织,空表示顶级 */
private Long parentId;
@NotBlank(message = "请填写组织名称")
@Size(max = 128, message = "组织名称不能超过128字")
private String name;
@Size(max = 64, message = "组织编码不能超过64字")
private String code;
private Integer sortNo;
/** 1启用 0停用 */
private Integer status;
@Size(max = 256, message = "备注不能超过256字")
private String remark;
}
@@ -0,0 +1,21 @@
package com.banben.modules.admin.dto;
import lombok.Data;
import java.util.List;
/**
* 组织树节点。叶子节点不带 children。
*/
@Data
public class OrgTreeVO {
private Long id;
private Long parentId;
private String name;
private String code;
private Integer sortNo;
private Integer status;
private String remark;
private List<OrgTreeVO> children;
}
@@ -0,0 +1,33 @@
package com.banben.modules.admin.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.util.List;
/**
* 新增或修改角色。
*/
@Data
public class RoleSaveRequest {
@NotBlank(message = "请填写角色编码")
@Size(max = 32, message = "角色编码不能超过32字")
@Pattern(regexp = "[A-Za-z][A-Za-z0-9_]{0,31}", message = "角色编码需以字母开头,只能包含字母、数字和下划线")
private String code;
@NotBlank(message = "请填写角色名称")
@Size(max = 64, message = "角色名称不能超过64字")
private String name;
@Size(max = 256, message = "备注不能超过256字")
private String remark;
/** 1启用 0停用 */
private Integer status;
/** 顶部导航编码。空列表表示该角色看不到任何顶部栏目。 */
private List<String> menuCodes;
}
@@ -0,0 +1,32 @@
package com.banben.modules.admin.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
/**
* 新增或修改用户。修改时密码留空表示不改密码。
*/
@Data
public class UserSaveRequest {
@NotBlank(message = "请填写登录账号")
@Size(max = 64, message = "登录账号不能超过64字")
private String username;
@Size(max = 64, message = "密码不能超过64字")
private String password;
@NotBlank(message = "请填写姓名")
@Size(max = 128, message = "姓名不能超过128字")
private String realName;
@NotNull(message = "请选择角色")
private Long roleId;
private Long orgId;
/** 1启用 0停用 */
private Integer status;
}
@@ -0,0 +1,24 @@
package com.banben.modules.admin.dto;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 用户列表行,不包含密码。
*/
@Data
public class UserVO {
private Long id;
private String username;
private String realName;
private Long roleId;
private String roleCode;
private String roleName;
private Long orgId;
private String orgName;
private Integer status;
private LocalDateTime lastLoginTime;
private LocalDateTime createTime;
}
@@ -0,0 +1,52 @@
package com.banben.modules.admin.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;
/**
* 多层级组织。
*/
@Data
@TableName("sys_org")
@Schema(description = "组织")
public class SysOrg implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
@Schema(description = "上级组织,空为顶级")
private Long parentId;
@Schema(description = "组织名称")
private String name;
@Schema(description = "组织编码")
private String code;
@Schema(description = "同级排序,小的在前")
private Integer sortNo;
@Schema(description = "1启用 0停用")
private Integer status;
@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,58 @@
package com.banben.modules.admin.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.ArrayList;
import java.util.List;
/**
* 角色。内置角色不可删除,编码供登录令牌使用。
*/
@Data
@TableName("sys_role")
@Schema(description = "角色")
public class SysRole implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
@Schema(description = "角色编码")
private String code;
@Schema(description = "角色名称")
private String name;
@Schema(description = "备注")
private String remark;
@Schema(description = "1启用 0停用")
private Integer status;
@Schema(description = "1内置 0自建")
private Integer builtin;
@Schema(description = "1表示顶部导航已初始化")
private Integer menuInited;
@TableField(exist = false)
@Schema(description = "可访问的顶部导航编码")
private List<String> menuCodes = new ArrayList<>();
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableLogic
private Integer deleted;
}
@@ -0,0 +1,23 @@
package com.banben.modules.admin.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* 角色与顶部导航的对应关系。
*/
@Data
@TableName("sys_role_menu")
public class SysRoleMenu implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
private Long roleId;
private String menuCode;
}
@@ -0,0 +1,12 @@
package com.banben.modules.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.admin.entity.SysOrg;
import org.apache.ibatis.annotations.Mapper;
/**
* 组织 Mapper。
*/
@Mapper
public interface SysOrgMapper extends BaseMapper<SysOrg> {
}
@@ -0,0 +1,12 @@
package com.banben.modules.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.admin.entity.SysRole;
import org.apache.ibatis.annotations.Mapper;
/**
* 角色 Mapper。
*/
@Mapper
public interface SysRoleMapper extends BaseMapper<SysRole> {
}
@@ -0,0 +1,12 @@
package com.banben.modules.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.admin.entity.SysRoleMenu;
import org.apache.ibatis.annotations.Mapper;
/**
* 角色导航权限。
*/
@Mapper
public interface SysRoleMenuMapper extends BaseMapper<SysRoleMenu> {
}
@@ -0,0 +1,24 @@
package com.banben.modules.admin.service;
import com.banben.modules.admin.dto.OrgSaveRequest;
import com.banben.modules.admin.dto.OrgTreeVO;
import java.util.List;
import java.util.Set;
/**
* 多层级组织。
*/
public interface OrgService {
List<OrgTreeVO> tree();
void create(OrgSaveRequest request);
void update(Long id, OrgSaveRequest request);
void remove(Long id);
/** 本级及全部下级的 id,含自身。 */
Set<Long> subtreeIds(Long orgId);
}
@@ -0,0 +1,22 @@
package com.banben.modules.admin.service;
import com.banben.modules.admin.dto.RoleSaveRequest;
import com.banben.modules.admin.entity.SysRole;
import java.util.List;
/**
* 角色维护。内置角色不可删除,编码变更时同步用户表上的角色编码。
*/
public interface RoleService {
List<SysRole> listAll();
void create(RoleSaveRequest request);
void update(Long id, RoleSaveRequest request);
void remove(Long id);
void ensureBuiltin();
}
@@ -0,0 +1,19 @@
package com.banben.modules.admin.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.banben.modules.admin.dto.UserSaveRequest;
import com.banben.modules.admin.dto.UserVO;
/**
* 用户管理。
*/
public interface UserAdminService {
Page<UserVO> page(long current, long size, String keyword, Long orgId, Long roleId);
void create(UserSaveRequest request);
void update(Long id, UserSaveRequest request);
void remove(Long id);
}
@@ -0,0 +1,376 @@
package com.banben.modules.admin.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.common.BusinessException;
import com.banben.modules.admin.dto.UserSaveRequest;
import com.banben.modules.admin.entity.SysOrg;
import com.banben.modules.admin.entity.SysRole;
import com.banben.modules.admin.mapper.SysOrgMapper;
import com.banben.modules.admin.mapper.SysRoleMapper;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import com.banben.modules.resource.dto.ImportResult;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 用户导入模板与批量导入。
*
* <p>模板第 1 行是表头,第 2 行是说明,第 3 行起为数据。账号已存在时更新该用户,密码留空则不改原密码。</p>
*/
@Service
@RequiredArgsConstructor
public class UserExcelService {
private static final String[] HEADERS = {"登录账号*", "姓名*", "初始密码", "角色编码*", "组织编码", "状态"};
private static final String[] HINTS = {
"必填。示例行以「示例:」开头,导入时自动跳过",
"必填",
"选填。新增留空则为 123456;更新留空则不修改密码",
"必填。填角色编码,见「可选数据」页",
"选填。填组织编码,或「上级/本级」路径",
"选填。启用 或 停用,默认启用"
};
private static final String[] SAMPLE = {"示例:zhangsan", "张三", "123456", "USER", "", "启用"};
private final SysUserMapper userMapper;
private final SysRoleMapper roleMapper;
private final SysOrgMapper orgMapper;
private final UserAdminService userAdminService;
private final DataFormatter formatter = new DataFormatter();
public void writeTemplate(OutputStream out) throws IOException {
List<SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<SysRole>().orderByAsc(SysRole::getId));
List<SysOrg> orgs = orgMapper.selectList(new LambdaQueryWrapper<SysOrg>().orderByAsc(SysOrg::getSortNo).orderByAsc(SysOrg::getId));
Map<Long, SysOrg> byId = new HashMap<>();
for (SysOrg org : orgs) {
byId.put(org.getId(), org);
}
try (XSSFWorkbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("用户");
CellStyle headStyle = headStyle(wb);
CellStyle hintStyle = hintStyle(wb);
Row head = sheet.createRow(0);
Row hint = sheet.createRow(1);
head.setHeightInPoints(22);
hint.setHeightInPoints(32);
int[] widths = {22, 16, 28, 22, 28, 16};
for (int i = 0; i < HEADERS.length; i++) {
Cell h = head.createCell(i);
h.setCellValue(HEADERS[i]);
h.setCellStyle(headStyle);
Cell t = hint.createCell(i);
t.setCellValue(HINTS[i]);
t.setCellStyle(hintStyle);
sheet.setColumnWidth(i, widths[i] * 256);
}
Row sample = sheet.createRow(2);
for (int i = 0; i < SAMPLE.length; i++) {
sample.createCell(i).setCellValue(SAMPLE[i]);
}
sheet.createFreezePane(0, 2);
Sheet dict = wb.createSheet("可选数据");
Row dictHead = dict.createRow(0);
dictHead.createCell(0).setCellValue("角色编码");
dictHead.createCell(1).setCellValue("角色名称");
dictHead.createCell(2).setCellValue("组织编码");
dictHead.createCell(3).setCellValue("组织路径");
for (int i = 0; i < roles.size(); i++) {
Row row = dict.createRow(i + 1);
row.createCell(0).setCellValue(roles.get(i).getCode());
row.createCell(1).setCellValue(roles.get(i).getName());
}
int orgRow = 1;
for (SysOrg org : orgs) {
Row row = dict.getRow(orgRow);
if (row == null) {
row = dict.createRow(orgRow);
}
row.createCell(2).setCellValue(org.getCode() == null ? "" : org.getCode());
row.createCell(3).setCellValue(pathOf(org, byId));
orgRow++;
}
dict.setColumnWidth(0, 18 * 256);
dict.setColumnWidth(1, 18 * 256);
dict.setColumnWidth(2, 18 * 256);
dict.setColumnWidth(3, 36 * 256);
if (!roles.isEmpty()) {
dropdown(sheet, 3, "'可选数据'!$A$2:$A$" + (roles.size() + 1));
}
dropdown(sheet, 5, "\"启用,停用\"");
wb.setActiveSheet(0);
wb.write(out);
}
}
public ImportResult importExcel(MultipartFile file) throws IOException {
ImportResult result = new ImportResult();
if (file == null || file.isEmpty()) {
result.addError(0, "请选择要导入的 Excel 文件");
return result;
}
List<SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<>());
List<SysOrg> orgs = orgMapper.selectList(new LambdaQueryWrapper<>());
Map<Long, SysOrg> byId = new HashMap<>();
for (SysOrg org : orgs) {
byId.put(org.getId(), org);
}
try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
Sheet sheet = wb.getNumberOfSheets() == 0 ? null : wb.getSheetAt(0);
if (sheet == null || sheet.getLastRowNum() < 1) {
result.addError(0, "表格为空,请使用系统导出的导入模板");
return result;
}
Map<String, Integer> columns = headerIndex(sheet.getRow(0));
if (!columns.containsKey("登录账号") || !columns.containsKey("姓名") || !columns.containsKey("角色编码")) {
result.addError(1, "表头缺少登录账号、姓名或角色编码,请使用系统导出的导入模板");
return result;
}
int start = hintRow(sheet) ? 2 : 1;
for (int r = start; r <= sheet.getLastRowNum(); r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
String username = cell(row, columns.get("登录账号"));
String realName = cell(row, columns.get("姓名"));
String password = cell(row, columns.get("初始密码"));
String roleText = cell(row, columns.get("角色编码"));
String orgText = cell(row, columns.get("组织编码"));
String statusText = cell(row, columns.get("状态"));
if (!StringUtils.hasText(username) && !StringUtils.hasText(realName)
&& !StringUtils.hasText(roleText)) {
continue;
}
int excelRow = r + 1;
if (isSample(username) || isSample(realName)) {
result.setSkipped(result.getSkipped() + 1);
continue;
}
result.setTotal(result.getTotal() + 1);
try {
importRow(username, realName, password, roleText, orgText, statusText, roles, orgs, byId, result);
} catch (BusinessException e) {
result.addError(excelRow, e.getMessage());
}
}
if (result.getTotal() == 0 && result.getFailed() == 0) {
result.addError(0, result.getSkipped() > 0
? "仅读取到模板示例数据,请填写实际数据后再导入"
: "未读取到有效数据行,请从第 3 行开始填写");
}
return result;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
result.addError(0, "文件解析失败:" + e.getMessage());
return result;
}
}
private void importRow(String username, String realName, String password, String roleText, String orgText,
String statusText, List<SysRole> roles, List<SysOrg> orgs, Map<Long, SysOrg> byId,
ImportResult result) {
if (!StringUtils.hasText(username)) {
throw new BusinessException("登录账号不能为空");
}
if (!StringUtils.hasText(realName)) {
throw new BusinessException("姓名不能为空");
}
SysRole role = matchRole(roleText, roles);
if (role == null) {
throw new BusinessException("角色不存在:" + roleText);
}
Long orgId = matchOrg(orgText, orgs, byId);
Integer status = parseStatus(statusText);
SysUser existing = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
.eq(SysUser::getUsername, username.trim()));
UserSaveRequest request = new UserSaveRequest();
request.setUsername(username.trim());
request.setRealName(realName.trim());
request.setPassword(StringUtils.hasText(password) ? password.trim() : null);
request.setRoleId(role.getId());
request.setOrgId(orgId);
request.setStatus(status);
if (existing == null) {
userAdminService.create(request);
result.setInserted(result.getInserted() + 1);
} else {
userAdminService.update(existing.getId(), request);
result.setUpdated(result.getUpdated() + 1);
}
}
private SysRole matchRole(String text, List<SysRole> roles) {
if (!StringUtils.hasText(text)) {
throw new BusinessException("角色编码不能为空");
}
String value = text.trim();
for (SysRole role : roles) {
if (role.getCode() != null && role.getCode().equalsIgnoreCase(value)) {
return role;
}
}
for (SysRole role : roles) {
if (value.equals(role.getName())) {
return role;
}
}
return null;
}
private Long matchOrg(String text, List<SysOrg> orgs, Map<Long, SysOrg> byId) {
if (!StringUtils.hasText(text)) {
return null;
}
String value = text.trim();
for (SysOrg org : orgs) {
if (value.equals(org.getCode())) {
return org.getId();
}
}
List<SysOrg> byPath = new ArrayList<>();
List<SysOrg> byName = new ArrayList<>();
for (SysOrg org : orgs) {
if (value.equals(pathOf(org, byId))) {
byPath.add(org);
}
if (value.equals(org.getName())) {
byName.add(org);
}
}
if (byPath.size() == 1) {
return byPath.get(0).getId();
}
if (byName.size() == 1) {
return byName.get(0).getId();
}
if (byName.size() > 1) {
throw new BusinessException("组织名称不唯一,请填写组织编码");
}
throw new BusinessException("组织不存在:" + value);
}
private Integer parseStatus(String text) {
if (!StringUtils.hasText(text) || "启用".equals(text.trim()) || "1".equals(text.trim())) {
return 1;
}
if ("停用".equals(text.trim()) || "0".equals(text.trim())) {
return 0;
}
throw new BusinessException("状态只能填启用或停用");
}
private String pathOf(SysOrg org, Map<Long, SysOrg> byId) {
LinkedHashMap<Long, String> guard = new LinkedHashMap<>();
List<String> parts = new ArrayList<>();
SysOrg cursor = org;
while (cursor != null && guard.put(cursor.getId(), cursor.getName()) == null) {
parts.add(0, cursor.getName());
cursor = cursor.getParentId() == null ? null : byId.get(cursor.getParentId());
}
return String.join("/", parts);
}
private Map<String, Integer> headerIndex(Row head) {
Map<String, Integer> columns = new HashMap<>();
if (head == null) {
return columns;
}
for (Cell cell : head) {
String name = formatter.formatCellValue(cell).replace("*", "").replace("*", "").trim();
if (StringUtils.hasText(name)) {
columns.put(name, cell.getColumnIndex());
}
}
return columns;
}
private boolean hintRow(Sheet sheet) {
Row second = sheet.getRow(1);
if (second == null) {
return false;
}
String first = formatter.formatCellValue(second.getCell(0));
return first.startsWith("必填") || first.startsWith("选填");
}
private String cell(Row row, Integer index) {
if (index == null) {
return "";
}
return formatter.formatCellValue(row.getCell(index)).trim();
}
private boolean isSample(String value) {
return value != null && (value.startsWith("示例:") || value.startsWith("示例:"));
}
private void dropdown(Sheet sheet, int column, String formula) {
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = formula.startsWith("\"")
? helper.createExplicitListConstraint(new String[]{"启用", "停用"})
: helper.createFormulaListConstraint(formula);
CellRangeAddressList range = new CellRangeAddressList(2, 5000, column, column);
DataValidation validation = helper.createValidation(constraint, range);
validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
}
private CellStyle headStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setBold(true);
font.setColor(IndexedColors.WHITE.getIndex());
style.setFont(font);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
private CellStyle hintStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setFontHeightInPoints((short) 9);
font.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFont(font);
style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setWrapText(true);
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
}
@@ -0,0 +1,215 @@
package com.banben.modules.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.banben.common.BusinessException;
import com.banben.modules.admin.dto.OrgSaveRequest;
import com.banben.modules.admin.dto.OrgTreeVO;
import com.banben.modules.admin.entity.SysOrg;
import com.banben.modules.admin.mapper.SysOrgMapper;
import com.banben.modules.admin.service.OrgService;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 组织树的增删改。删除时若仍有下级或用户则拒绝。
*/
@Service
@RequiredArgsConstructor
public class OrgServiceImpl implements OrgService {
private final SysOrgMapper orgMapper;
private final SysUserMapper userMapper;
@Override
public List<OrgTreeVO> tree() {
List<SysOrg> all = orgMapper.selectList(new LambdaQueryWrapper<SysOrg>()
.orderByAsc(SysOrg::getSortNo)
.orderByAsc(SysOrg::getId));
Map<Long, OrgTreeVO> nodes = new HashMap<>();
for (SysOrg org : all) {
nodes.put(org.getId(), toVo(org));
}
List<OrgTreeVO> roots = new ArrayList<>();
for (SysOrg org : all) {
OrgTreeVO node = nodes.get(org.getId());
OrgTreeVO parent = org.getParentId() == null ? null : nodes.get(org.getParentId());
if (parent == null) {
roots.add(node);
} else {
if (parent.getChildren() == null) {
parent.setChildren(new ArrayList<>());
}
parent.getChildren().add(node);
}
}
sortTree(roots);
return roots;
}
@Override
public void create(OrgSaveRequest request) {
SysOrg org = new SysOrg();
fill(org, request, null);
orgMapper.insert(org);
}
@Override
public void update(Long id, OrgSaveRequest request) {
SysOrg org = require(id);
fill(org, request, id);
orgMapper.update(null, new LambdaUpdateWrapper<SysOrg>()
.eq(SysOrg::getId, id)
.set(SysOrg::getParentId, org.getParentId())
.set(SysOrg::getName, org.getName())
.set(SysOrg::getCode, org.getCode())
.set(SysOrg::getSortNo, org.getSortNo())
.set(SysOrg::getStatus, org.getStatus())
.set(SysOrg::getRemark, org.getRemark()));
syncUserOrgName(org);
}
@Override
public void remove(Long id) {
require(id);
Long children = orgMapper.selectCount(new LambdaQueryWrapper<SysOrg>().eq(SysOrg::getParentId, id));
if (children != null && children > 0) {
throw new BusinessException("请先删除下级组织");
}
Long users = userMapper.selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOrgId, id));
if (users != null && users > 0) {
throw new BusinessException("该组织下还有用户,不能删除");
}
orgMapper.deleteById(id);
}
@Override
public Set<Long> subtreeIds(Long orgId) {
require(orgId);
List<SysOrg> all = orgMapper.selectList(new LambdaQueryWrapper<>());
Map<Long, List<Long>> children = new HashMap<>();
for (SysOrg org : all) {
if (org.getParentId() != null) {
children.computeIfAbsent(org.getParentId(), key -> new ArrayList<>()).add(org.getId());
}
}
Set<Long> ids = new HashSet<>();
collect(orgId, children, ids);
return ids;
}
private void collect(Long id, Map<Long, List<Long>> children, Set<Long> ids) {
if (!ids.add(id)) {
return;
}
for (Long child : children.getOrDefault(id, List.of())) {
collect(child, children, ids);
}
}
private void fill(SysOrg org, OrgSaveRequest request, Long selfId) {
Long parentId = request.getParentId();
if (parentId != null) {
if (parentId.equals(selfId)) {
throw new BusinessException("上级组织不能是自己");
}
require(parentId);
assertNoCycle(selfId, parentId);
}
String code = blankToNull(request.getCode());
assertCodeUnique(code, selfId);
org.setParentId(parentId);
org.setName(request.getName().trim());
org.setCode(code);
org.setSortNo(request.getSortNo() == null ? 0 : request.getSortNo());
org.setStatus(request.getStatus() != null && request.getStatus() == 0 ? 0 : 1);
org.setRemark(blankToNull(request.getRemark()));
}
private void assertNoCycle(Long selfId, Long parentId) {
if (selfId == null) {
return;
}
Long cursor = parentId;
Set<Long> seen = new HashSet<>();
while (cursor != null) {
if (cursor.equals(selfId)) {
throw new BusinessException("不能把组织移动到自己的下级");
}
if (!seen.add(cursor)) {
break;
}
SysOrg parent = orgMapper.selectById(cursor);
cursor = parent == null ? null : parent.getParentId();
}
}
private void assertCodeUnique(String code, Long selfId) {
if (code == null) {
return;
}
LambdaQueryWrapper<SysOrg> query = new LambdaQueryWrapper<SysOrg>().eq(SysOrg::getCode, code);
if (selfId != null) {
query.ne(SysOrg::getId, selfId);
}
Long count = orgMapper.selectCount(query);
if (count != null && count > 0) {
throw new BusinessException("组织编码已存在");
}
}
private void syncUserOrgName(SysOrg org) {
SysUser patch = new SysUser();
patch.setOrgName(org.getName());
userMapper.update(patch, new LambdaQueryWrapper<SysUser>().eq(SysUser::getOrgId, org.getId()));
}
private SysOrg require(Long id) {
SysOrg org = orgMapper.selectById(id);
if (org == null) {
throw new BusinessException("组织不存在");
}
return org;
}
private OrgTreeVO toVo(SysOrg org) {
OrgTreeVO vo = new OrgTreeVO();
vo.setId(org.getId());
vo.setParentId(org.getParentId());
vo.setName(org.getName());
vo.setCode(org.getCode());
vo.setSortNo(org.getSortNo());
vo.setStatus(org.getStatus());
vo.setRemark(org.getRemark());
return vo;
}
private void sortTree(List<OrgTreeVO> nodes) {
nodes.sort(Comparator
.comparing((OrgTreeVO node) -> node.getSortNo() == null ? 0 : node.getSortNo())
.thenComparing(OrgTreeVO::getId));
for (OrgTreeVO node : nodes) {
if (node.getChildren() != null) {
sortTree(node.getChildren());
}
}
}
private String blankToNull(String value) {
if (!StringUtils.hasText(value)) {
return null;
}
return value.trim();
}
}
@@ -0,0 +1,193 @@
package com.banben.modules.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.banben.common.BusinessException;
import com.banben.modules.admin.dto.RoleSaveRequest;
import com.banben.modules.admin.entity.SysRole;
import com.banben.modules.admin.entity.SysRoleMenu;
import com.banben.modules.admin.mapper.SysRoleMapper;
import com.banben.modules.admin.mapper.SysRoleMenuMapper;
import com.banben.modules.admin.service.RoleService;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import com.banben.modules.auth.nav.NavMenus;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 角色增删改。ADMIN、USER 为内置角色。
*/
@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {
private final SysRoleMapper roleMapper;
private final SysRoleMenuMapper roleMenuMapper;
private final SysUserMapper userMapper;
@Override
public List<SysRole> listAll() {
List<SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<SysRole>()
.orderByDesc(SysRole::getBuiltin)
.orderByAsc(SysRole::getId));
Map<Long, List<String>> menus = roleMenuMapper.selectList(new LambdaQueryWrapper<>()).stream()
.collect(Collectors.groupingBy(SysRoleMenu::getRoleId,
Collectors.mapping(SysRoleMenu::getMenuCode, Collectors.toList())));
for (SysRole role : roles) {
if (isAdminCode(role)) {
role.setMenuCodes(new ArrayList<>(NavMenus.CODES));
continue;
}
role.setMenuCodes(menus.getOrDefault(role.getId(), List.of()).stream()
.filter(NavMenus::contains)
.distinct()
.toList());
}
return roles;
}
@Override
public void create(RoleSaveRequest request) {
SysRole role = new SysRole();
role.setBuiltin(0);
fill(role, request, null);
roleMapper.insert(role);
replaceMenus(role.getId(), request.getMenuCodes());
markMenusInited(role.getId());
}
@Override
public void update(Long id, RoleSaveRequest request) {
SysRole role = require(id);
String previousCode = role.getCode();
if (isBuiltin(role) && !previousCode.equalsIgnoreCase(request.getCode().trim())) {
throw new BusinessException("内置角色不能修改编码");
}
fill(role, request, id);
roleMapper.update(null, new LambdaUpdateWrapper<SysRole>()
.eq(SysRole::getId, id)
.set(SysRole::getCode, role.getCode())
.set(SysRole::getName, role.getName())
.set(SysRole::getRemark, role.getRemark())
.set(SysRole::getStatus, role.getStatus()));
if (!previousCode.equals(role.getCode())) {
userMapper.update(null, new LambdaUpdateWrapper<SysUser>()
.set(SysUser::getRole, role.getCode())
.eq(SysUser::getRoleId, id));
}
if (isAdminCode(role)) {
replaceMenus(id, NavMenus.CODES);
markMenusInited(id);
} else if (request.getMenuCodes() != null) {
replaceMenus(id, request.getMenuCodes());
markMenusInited(id);
}
}
@Override
public void remove(Long id) {
SysRole role = require(id);
if (isBuiltin(role)) {
throw new BusinessException("内置角色不能删除");
}
Long users = userMapper.selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getRoleId, id));
if (users != null && users > 0) {
throw new BusinessException("该角色下还有用户,不能删除");
}
roleMapper.deleteById(id);
roleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, id));
}
@Override
public void ensureBuiltin() {
ensure("ADMIN", "系统管理员", "系统内置,可管理组织、用户与角色");
ensure("USER", "普通用户", "系统内置普通用户");
}
private void ensure(String code, String name, String remark) {
SysRole existing = roleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, code));
if (existing != null) {
if ("ADMIN".equalsIgnoreCase(code)) {
replaceMenus(existing.getId(), NavMenus.CODES);
markMenusInited(existing.getId());
}
return;
}
SysRole role = new SysRole();
role.setCode(code);
role.setName(name);
role.setRemark(remark);
role.setStatus(1);
role.setBuiltin(1);
roleMapper.insert(role);
replaceMenus(role.getId(), NavMenus.CODES);
markMenusInited(role.getId());
}
private void fill(SysRole role, RoleSaveRequest request, Long selfId) {
String code = request.getCode().trim().toUpperCase();
LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, code);
if (selfId != null) {
query.ne(SysRole::getId, selfId);
}
Long count = roleMapper.selectCount(query);
if (count != null && count > 0) {
throw new BusinessException("角色编码已存在");
}
role.setCode(code);
role.setName(request.getName().trim());
role.setRemark(StringUtils.hasText(request.getRemark()) ? request.getRemark().trim() : null);
role.setStatus(request.getStatus() != null && request.getStatus() == 0 ? 0 : 1);
}
private SysRole require(Long id) {
SysRole role = roleMapper.selectById(id);
if (role == null) {
throw new BusinessException("角色不存在");
}
return role;
}
private boolean isBuiltin(SysRole role) {
return role.getBuiltin() != null && role.getBuiltin() == 1;
}
private boolean isAdminCode(SysRole role) {
return role.getCode() != null && "ADMIN".equalsIgnoreCase(role.getCode());
}
private void replaceMenus(Long roleId, List<String> menuCodes) {
List<String> codes = menuCodes == null ? new ArrayList<>(NavMenus.CODES) : normalize(menuCodes);
roleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleId));
for (String code : codes) {
SysRoleMenu row = new SysRoleMenu();
row.setRoleId(roleId);
row.setMenuCode(code);
roleMenuMapper.insert(row);
}
}
private List<String> normalize(List<String> menuCodes) {
LinkedHashSet<String> codes = new LinkedHashSet<>();
for (String code : menuCodes) {
if (NavMenus.contains(code)) {
codes.add(code);
}
}
return new ArrayList<>(codes);
}
private void markMenusInited(Long roleId) {
roleMapper.update(null, new LambdaUpdateWrapper<SysRole>()
.eq(SysRole::getId, roleId)
.set(SysRole::getMenuInited, 1));
}
}
@@ -0,0 +1,216 @@
package com.banben.modules.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.banben.common.BusinessException;
import com.banben.modules.admin.dto.UserSaveRequest;
import com.banben.modules.admin.dto.UserVO;
import com.banben.modules.admin.entity.SysOrg;
import com.banben.modules.admin.entity.SysRole;
import com.banben.modules.admin.mapper.SysOrgMapper;
import com.banben.modules.admin.mapper.SysRoleMapper;
import com.banben.modules.admin.service.OrgService;
import com.banben.modules.admin.service.UserAdminService;
import com.banben.modules.auth.context.UserContext;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 用户新增、修改、删除。密码留空时,新增使用 123456,修改则保持原密码。
*/
@Service
@RequiredArgsConstructor
public class UserAdminServiceImpl implements UserAdminService {
static final String DEFAULT_PASSWORD = "123456";
private final SysUserMapper userMapper;
private final SysRoleMapper roleMapper;
private final SysOrgMapper orgMapper;
private final OrgService orgService;
private final PasswordEncoder passwordEncoder;
@Override
public Page<UserVO> page(long current, long size, String keyword, Long orgId, Long roleId) {
LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
if (StringUtils.hasText(keyword)) {
String word = keyword.trim();
query.and(w -> w.like(SysUser::getUsername, word).or().like(SysUser::getRealName, word));
}
if (orgId != null) {
query.in(SysUser::getOrgId, orgService.subtreeIds(orgId));
}
if (roleId != null) {
query.eq(SysUser::getRoleId, roleId);
}
query.orderByDesc(SysUser::getId);
Page<SysUser> raw = userMapper.selectPage(new Page<>(current, size), query);
Map<Long, SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<>()).stream()
.collect(Collectors.toMap(SysRole::getId, role -> role, (a, b) -> a));
Map<Long, SysOrg> orgs = orgMapper.selectList(new LambdaQueryWrapper<>()).stream()
.collect(Collectors.toMap(SysOrg::getId, org -> org, (a, b) -> a));
Page<UserVO> page = new Page<>(raw.getCurrent(), raw.getSize(), raw.getTotal());
page.setRecords(raw.getRecords().stream().map(user -> toVo(user, roles, orgs)).toList());
return page;
}
@Override
public void create(UserSaveRequest request) {
SysRole role = requireRole(request.getRoleId());
SysOrg org = optionalOrg(request.getOrgId());
assertUsernameFree(request.getUsername().trim(), null);
assertPassword(request.getPassword(), true);
SysUser user = new SysUser();
user.setUsername(request.getUsername().trim());
user.setPassword(passwordEncoder.encode(passwordOrDefault(request.getPassword())));
user.setRealName(request.getRealName().trim());
user.setRoleId(role.getId());
user.setRole(role.getCode());
user.setOrgId(org == null ? null : org.getId());
user.setOrgName(org == null ? null : org.getName());
user.setStatus(statusOf(request.getStatus()));
try {
userMapper.insert(user);
} catch (DuplicateKeyException e) {
throw new BusinessException("登录账号已存在");
}
}
@Override
public void update(Long id, UserSaveRequest request) {
SysUser existing = requireUser(id);
SysRole role = requireRole(request.getRoleId());
SysOrg org = optionalOrg(request.getOrgId());
assertUsernameFree(request.getUsername().trim(), id);
assertPassword(request.getPassword(), false);
guardLastAdmin(existing, role.getCode(), statusOf(request.getStatus()), false);
LambdaUpdateWrapper<SysUser> update = new LambdaUpdateWrapper<SysUser>()
.eq(SysUser::getId, id)
.set(SysUser::getUsername, request.getUsername().trim())
.set(SysUser::getRealName, request.getRealName().trim())
.set(SysUser::getRoleId, role.getId())
.set(SysUser::getRole, role.getCode())
.set(SysUser::getOrgId, org == null ? null : org.getId())
.set(SysUser::getOrgName, org == null ? null : org.getName())
.set(SysUser::getStatus, statusOf(request.getStatus()));
if (StringUtils.hasText(request.getPassword())) {
update.set(SysUser::getPassword, passwordEncoder.encode(request.getPassword().trim()));
}
try {
userMapper.update(null, update);
} catch (DuplicateKeyException e) {
throw new BusinessException("登录账号已存在");
}
}
@Override
public void remove(Long id) {
SysUser existing = requireUser(id);
if (id.equals(UserContext.currentUserId())) {
throw new BusinessException("不能删除当前登录账号");
}
guardLastAdmin(existing, null, 0, true);
userMapper.deleteById(id);
}
private void guardLastAdmin(SysUser existing, String nextRole, int nextStatus, boolean deleting) {
if (!"ADMIN".equalsIgnoreCase(existing.getRole())) {
return;
}
boolean stillAdmin = !deleting && "ADMIN".equalsIgnoreCase(nextRole) && nextStatus == 1;
if (stillAdmin) {
return;
}
Long admins = userMapper.selectCount(new LambdaQueryWrapper<SysUser>()
.eq(SysUser::getRole, "ADMIN")
.eq(SysUser::getStatus, 1)
.ne(SysUser::getId, existing.getId()));
if (admins == null || admins == 0) {
throw new BusinessException("至少保留一个启用的系统管理员");
}
}
private void assertUsernameFree(String username, Long selfId) {
LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username);
if (selfId != null) {
query.ne(SysUser::getId, selfId);
}
Long count = userMapper.selectCount(query);
if (count != null && count > 0) {
throw new BusinessException("登录账号已存在");
}
}
private SysUser requireUser(Long id) {
SysUser user = userMapper.selectById(id);
if (user == null) {
throw new BusinessException("用户不存在");
}
return user;
}
private SysRole requireRole(Long roleId) {
SysRole role = roleMapper.selectById(roleId);
if (role == null) {
throw new BusinessException("角色不存在");
}
return role;
}
private SysOrg optionalOrg(Long orgId) {
if (orgId == null) {
return null;
}
SysOrg org = orgMapper.selectById(orgId);
if (org == null) {
throw new BusinessException("组织不存在");
}
return org;
}
private int statusOf(Integer status) {
return status != null && status == 0 ? 0 : 1;
}
private String passwordOrDefault(String password) {
return StringUtils.hasText(password) ? password.trim() : DEFAULT_PASSWORD;
}
private void assertPassword(String password, boolean creating) {
if (!StringUtils.hasText(password)) {
return;
}
if (password.trim().length() < 6) {
throw new BusinessException(creating ? "密码至少 6 位,留空则使用 123456" : "密码至少 6 位");
}
}
private UserVO toVo(SysUser user, Map<Long, SysRole> roles, Map<Long, SysOrg> orgs) {
UserVO vo = new UserVO();
vo.setId(user.getId());
vo.setUsername(user.getUsername());
vo.setRealName(user.getRealName());
vo.setRoleId(user.getRoleId());
vo.setRoleCode(user.getRole());
SysRole role = user.getRoleId() == null ? null : roles.get(user.getRoleId());
vo.setRoleName(role == null ? user.getRole() : role.getName());
vo.setOrgId(user.getOrgId());
SysOrg org = user.getOrgId() == null ? null : orgs.get(user.getOrgId());
vo.setOrgName(org == null ? user.getOrgName() : org.getName());
vo.setStatus(user.getStatus());
vo.setLastLoginTime(user.getLastLoginTime());
vo.setCreateTime(user.getCreateTime());
return vo;
}
}
@@ -0,0 +1,59 @@
package com.banben.modules.admin.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.common.BusinessException;
import com.banben.modules.admin.entity.SysRoleMenu;
import com.banben.modules.admin.mapper.SysRoleMenuMapper;
import com.banben.modules.auth.context.LoginUser;
import com.banben.modules.auth.context.UserContext;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/**
* 后台管理接口:角色勾选了「后台管理」栏目才能调用。
* 权限表暂时不可用时,仍放行角色编码为 ADMIN 的账号,避免把管理员锁在外面。
*/
@Component
@RequiredArgsConstructor
public class AdminAccess {
private final SysUserMapper userMapper;
private final SysRoleMenuMapper roleMenuMapper;
public void require() {
LoginUser login = UserContext.get();
if (login == null || login.id() == null || !allowed(login.id(), login.role())) {
throw new BusinessException(403, "需要后台管理权限");
}
}
private boolean allowed(Long userId, String roleCode) {
if (isAdminCode(roleCode)) {
return true;
}
try {
SysUser user = userMapper.selectById(userId);
if (user == null) {
return false;
}
if (isAdminCode(user.getRole())) {
return true;
}
if (user.getRoleId() == null) {
return false;
}
Long count = roleMenuMapper.selectCount(new LambdaQueryWrapper<SysRoleMenu>()
.eq(SysRoleMenu::getRoleId, user.getRoleId())
.eq(SysRoleMenu::getMenuCode, "admin"));
return count != null && count > 0;
} catch (Exception ignored) {
return isAdminCode(roleCode);
}
}
private boolean isAdminCode(String roleCode) {
return roleCode != null && "ADMIN".equalsIgnoreCase(roleCode);
}
}
@@ -0,0 +1,51 @@
package com.banben.modules.auth;
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;
/**
* 登录日志表自举建表。
*
* <p>应用本身不在启动时自动执行建表脚本(dev/prod 的初始化脚本仅在数据库首次初始化时跑一次)。
* 但登录日志功能是后加的,已初始化的运行库里可能缺这张表,会导致 {@code /admin/login-logs/page}
* 直接抛 500。这里在容器就绪后幂等地补建该表,保证新库旧库都能正常工作,不影响已有数据。</p>
*/
@Slf4j
@Component
public class LoginLogTableInitializer {
private final JdbcTemplate jdbcTemplate;
public LoginLogTableInitializer(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@EventListener(ApplicationReadyEvent.class)
public void init() {
try {
jdbcTemplate.execute(
"CREATE TABLE IF NOT EXISTS login_log ("
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
+ "user_id BIGINT, "
+ "username VARCHAR(128), "
+ "real_name VARCHAR(128), "
+ "org_name VARCHAR(256), "
+ "ip VARCHAR(64), "
+ "user_agent VARCHAR(512), "
+ "login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
+ "logout_time TIMESTAMP, "
+ "online SMALLINT DEFAULT 1, "
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_user_id ON login_log (user_id)");
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_login_time ON login_log (login_time)");
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_online ON login_log (online)");
log.info("登录日志表 login_log 已就绪(不存在则已自动创建)");
} catch (Exception e) {
// 建表失败不应阻断启动;缺表时登录日志接口已做优雅降级
log.warn("自动创建 login_log 表失败(不影响启动,请检查数据库权限):{}", e.getMessage());
}
}
}
@@ -5,12 +5,16 @@ import com.banben.modules.auth.dto.LoginRequest;
import com.banben.modules.auth.dto.LoginResponse; import com.banben.modules.auth.dto.LoginResponse;
import com.banben.modules.auth.entity.SysUser; import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.service.AuthService; import com.banben.modules.auth.service.AuthService;
import com.banben.modules.auth.service.LoginLogService;
import com.banben.modules.auth.context.UserContext;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List;
/** /**
* 认证接口。 * 认证接口。
*/ */
@@ -21,6 +25,7 @@ import org.springframework.web.bind.annotation.*;
public class AuthController { public class AuthController {
private final AuthService authService; private final AuthService authService;
private final LoginLogService loginLogService;
@Operation(summary = "登录") @Operation(summary = "登录")
@PostMapping("/login") @PostMapping("/login")
@@ -34,10 +39,17 @@ public class AuthController {
return Result.success(authService.currentUser()); return Result.success(authService.currentUser());
} }
@Operation(summary = "当前用户可见的顶部导航")
@GetMapping("/menus")
public Result<List<String>> menus() {
return Result.success(authService.currentMenus());
}
@Operation(summary = "登出") @Operation(summary = "登出")
@PostMapping("/logout") @PostMapping("/logout")
public Result<Void> logout() { public Result<Void> logout() {
// 采用无状态 JWT,登出由前端清除本地令牌即可;此处预留服务端黑名单能力 // 采用无状态 JWT,登出由前端清除本地令牌即可;此处同时回填登录日志的退出时间
loginLogService.recordLogout(UserContext.currentUserId());
return Result.success(); return Result.success();
} }
} }
@@ -0,0 +1,76 @@
package com.banben.modules.auth.controller;
import com.banben.common.PageResult;
import com.banben.common.Result;
import com.banben.modules.admin.support.AdminAccess;
import com.banben.modules.auth.dto.LoginLogQuery;
import com.banben.modules.auth.entity.LoginLog;
import com.banben.modules.auth.service.LoginLogService;
import com.banben.modules.auth.vo.AccessDimensionItem;
import com.banben.modules.auth.vo.AccessOverview;
import com.banben.modules.auth.vo.AccessTrendPoint;
import com.banben.modules.auth.vo.LoginLogSummary;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
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;
/**
* 后台管理 - 登录日志。
*/
@Tag(name = "后台管理-登录日志")
@RestController
@RequestMapping("/api/admin/login-logs")
@RequiredArgsConstructor
public class LoginLogController {
private final LoginLogService loginLogService;
private final AdminAccess adminAccess;
@Operation(summary = "登录日志分页(支持账号/姓名/单位关键字、在线状态、登录时间区间)")
@GetMapping("/page")
public Result<PageResult<LoginLog>> page(LoginLogQuery query) {
adminAccess.require();
return Result.success(loginLogService.page(query));
}
@Operation(summary = "登录日志概览:会话总数 / 当前在线 / 今日登录")
@GetMapping("/summary")
public Result<LoginLogSummary> summary() {
adminAccess.require();
return Result.success(loginLogService.summary());
}
@Operation(summary = "网络访问概览:历史/本月/本周/今日 的人次与人数")
@GetMapping("/access-overview")
public Result<AccessOverview> accessOverview() {
adminAccess.require();
return Result.success(loginLogService.accessOverview());
}
@Operation(summary = "网络访问趋势:按 小时/日/周/月/年 分桶(可指定时段)")
@GetMapping("/access-trend")
public Result<List<AccessTrendPoint>> accessTrend(
@RequestParam(defaultValue = "hour") String granularity,
@RequestParam(required = false) String start,
@RequestParam(required = false) String end) {
adminAccess.require();
return Result.success(loginLogService.accessTrend(granularity, start, end));
}
@Operation(summary = "网络访问维度统计:按 IP/单位/账号/类型 分组(可指定时段)")
@GetMapping("/access-dimension")
public Result<List<AccessDimensionItem>> accessDimension(
@RequestParam(defaultValue = "ip") String dimension,
@RequestParam(required = false) String start,
@RequestParam(required = false) String end,
@RequestParam(defaultValue = "20") int limit) {
adminAccess.require();
return Result.success(loginLogService.accessDimension(dimension, start, end, limit));
}
}
@@ -0,0 +1,31 @@
package com.banben.modules.auth.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 登录日志查询条件。
*/
@Data
@Schema(description = "登录日志查询条件")
public class LoginLogQuery {
@Schema(description = "页码,从1开始", example = "1")
private Long current = 1L;
@Schema(description = "每页条数", example = "20")
private Long size = 20L;
@Schema(description = "关键字:匹配账号 / 姓名 / 单位")
private String keyword;
/** ONLINE 在线 / OFFLINE 离线 / 空 全部 */
@Schema(description = "状态:ONLINE 在线 / OFFLINE 离线 / 空 全部")
private String status;
@Schema(description = "登录时间起(含,yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss)")
private String loginStart;
@Schema(description = "登录时间止(含)")
private String loginEnd;
}
@@ -3,6 +3,8 @@ package com.banben.modules.auth.dto;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
import java.util.List;
/** /**
* 登录响应。 * 登录响应。
*/ */
@@ -27,4 +29,7 @@ public class LoginResponse {
@Schema(description = "所属单位") @Schema(description = "所属单位")
private String orgName; private String orgName;
@Schema(description = "可见的顶部导航编码")
private List<String> menus;
} }
@@ -0,0 +1,60 @@
package com.banben.modules.auth.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.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 用户登录日志(会话维度)。
*
* <p>一次成功登录产生一条会话记录:{@code online=1}、{@code logoutTime=null};
* 用户主动退出时回填 {@code logoutTime} 并置 {@code online=0}。
* 「在线」状态以 {@code logoutTime 为 null} 为准,前端据此展示在线/离线。</p>
*/
@Data
@TableName("login_log")
@Schema(description = "用户登录日志(会话维度:一次登录一条,登出置 logout_time)")
public class LoginLog implements Serializable {
@TableId(type = IdType.AUTO)
@Schema(description = "主键")
private Long id;
@Schema(description = "用户ID")
private Long userId;
@Schema(description = "登录账号")
private String username;
@Schema(description = "姓名")
private String realName;
@Schema(description = "所属单位")
private String orgName;
@Schema(description = "登录IP")
private String ip;
@Schema(description = "浏览器/客户端标识")
private String userAgent;
@Schema(description = "登录时间")
private LocalDateTime loginTime;
@Schema(description = "退出时间,未退出为 null")
private LocalDateTime logoutTime;
@Schema(description = "是否在线:1在线 0离线")
private Integer online;
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建时间")
private LocalDateTime createTime;
}
@@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
@@ -26,18 +27,25 @@ public class SysUser implements Serializable {
@Schema(description = "登录账号") @Schema(description = "登录账号")
private String username; private String username;
@JsonIgnore
@Schema(description = "BCrypt 加密后的密码") @Schema(description = "BCrypt 加密后的密码")
private String password; private String password;
@Schema(description = "姓名") @Schema(description = "姓名")
private String realName; private String realName;
@Schema(description = "角色:ADMIN / USER") @Schema(description = "角色编码,与 sys_role.code 一致,写入登录令牌")
private String role; private String role;
@Schema(description = "所属单位") @Schema(description = "角色,对应 sys_role.id")
private Long roleId;
@Schema(description = "所属单位名称,与组织名称同步")
private String orgName; private String orgName;
@Schema(description = "所属组织,对应 sys_org.id")
private Long orgId;
@Schema(description = "状态:1启用 0停用") @Schema(description = "状态:1启用 0停用")
private Integer status; private Integer status;
@@ -0,0 +1,10 @@
package com.banben.modules.auth.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.auth.entity.LoginLog;
/**
* 用户登录日志 Mapper。
*/
public interface LoginLogMapper extends BaseMapper<LoginLog> {
}
@@ -0,0 +1,30 @@
package com.banben.modules.auth.nav;
import java.util.List;
/**
* 顶部导航。编码与前端路由一致,角色按编码授权。
*/
public final class NavMenus {
public static final List<String> CODES = List.of(
"dashboard",
"search",
"hotwords",
"special",
"deposit",
"analysis",
"resource",
"collect",
"sync",
"governance",
"admin"
);
private NavMenus() {
}
public static boolean contains(String code) {
return code != null && CODES.contains(code);
}
}
@@ -4,6 +4,8 @@ import com.banben.modules.auth.dto.LoginRequest;
import com.banben.modules.auth.dto.LoginResponse; import com.banben.modules.auth.dto.LoginResponse;
import com.banben.modules.auth.entity.SysUser; import com.banben.modules.auth.entity.SysUser;
import java.util.List;
/** /**
* 认证服务。 * 认证服务。
*/ */
@@ -18,4 +20,9 @@ public interface AuthService {
* 查询当前登录用户完整信息。 * 查询当前登录用户完整信息。
*/ */
SysUser currentUser(); SysUser currentUser();
/**
* 当前用户可见的顶部导航编码。
*/
List<String> currentMenus();
} }
@@ -0,0 +1,38 @@
package com.banben.modules.auth.service;
import com.banben.common.PageResult;
import com.banben.modules.auth.dto.LoginLogQuery;
import com.banben.modules.auth.entity.LoginLog;
import com.banben.modules.auth.vo.AccessDimensionItem;
import com.banben.modules.auth.vo.AccessOverview;
import com.banben.modules.auth.vo.AccessTrendPoint;
import com.banben.modules.auth.vo.LoginLogSummary;
import java.util.List;
/**
* 用户登录日志服务。
*/
public interface LoginLogService {
/** 记录一次成功登录(会话开始)。 */
void recordLogin(Long userId, String username, String realName, String orgName, String ip, String userAgent);
/** 记录退出:回填该用户最近一条未退出的会话。 */
void recordLogout(Long userId);
/** 分页查询登录日志。 */
PageResult<LoginLog> page(LoginLogQuery query);
/** 概览统计:总数 / 在线 / 今日登录。 */
LoginLogSummary summary();
/** 网络访问概览:历史 / 本月 / 本周 / 今日 的人次与人数。 */
AccessOverview accessOverview();
/** 网络访问趋势:按 小时/日/周/月/年 分桶统计。 */
List<AccessTrendPoint> accessTrend(String granularity, String start, String end);
/** 网络访问维度统计:按 IP / 单位 / 账号 / 类型 分组。 */
List<AccessDimensionItem> accessDimension(String dimension, String start, String end, int limit);
}
@@ -1,20 +1,32 @@
package com.banben.modules.auth.service.impl; package com.banben.modules.auth.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.common.BusinessException; import com.banben.common.BusinessException;
import com.banben.modules.auth.context.UserContext; import com.banben.modules.auth.context.UserContext;
import com.banben.modules.auth.dto.LoginRequest; import com.banben.modules.auth.dto.LoginRequest;
import com.banben.modules.auth.dto.LoginResponse; import com.banben.modules.auth.dto.LoginResponse;
import com.banben.modules.admin.entity.SysRole;
import com.banben.modules.admin.entity.SysRoleMenu;
import com.banben.modules.admin.mapper.SysRoleMapper;
import com.banben.modules.admin.mapper.SysRoleMenuMapper;
import com.banben.modules.auth.entity.SysUser; import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper; import com.banben.modules.auth.mapper.SysUserMapper;
import com.banben.modules.auth.nav.NavMenus;
import com.banben.modules.auth.service.AuthService; import com.banben.modules.auth.service.AuthService;
import com.banben.modules.auth.service.LoginLogService;
import com.banben.modules.auth.util.JwtUtil; import com.banben.modules.auth.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/** /**
* 认证服务实现。 * 认证服务实现。
@@ -25,8 +37,11 @@ import java.time.LocalDateTime;
public class AuthServiceImpl implements AuthService { public class AuthServiceImpl implements AuthService {
private final SysUserMapper sysUserMapper; private final SysUserMapper sysUserMapper;
private final SysRoleMapper sysRoleMapper;
private final SysRoleMenuMapper roleMenuMapper;
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
private final JwtUtil jwtUtil; private final JwtUtil jwtUtil;
private final LoginLogService loginLogService;
@Override @Override
public LoginResponse login(LoginRequest request) { public LoginResponse login(LoginRequest request) {
@@ -40,10 +55,23 @@ public class AuthServiceImpl implements AuthService {
if (user.getStatus() != null && user.getStatus() == 0) { if (user.getStatus() != null && user.getStatus() == 0) {
throw new BusinessException("账号已停用,请联系管理员"); throw new BusinessException("账号已停用,请联系管理员");
} }
if (user.getRoleId() != null) {
SysRole role = sysRoleMapper.selectById(user.getRoleId());
if (role == null || (role.getStatus() != null && role.getStatus() == 0)) {
throw new BusinessException("角色已停用,请联系管理员");
}
user.setRole(role.getCode());
}
user.setLastLoginTime(LocalDateTime.now()); user.setLastLoginTime(LocalDateTime.now());
sysUserMapper.updateById(user); sysUserMapper.updateById(user);
// 记录登录日志(会话维度):取客户端 IP 与 UA
HttpServletRequest httpReq = currentRequest();
String ip = httpReq == null ? null : clientIp(httpReq);
String ua = httpReq == null ? null : httpReq.getHeader("User-Agent");
loginLogService.recordLogin(user.getId(), user.getUsername(), user.getRealName(), user.getOrgName(), ip, ua);
String token = jwtUtil.generate(user.getId(), user.getUsername(), user.getRole()); String token = jwtUtil.generate(user.getId(), user.getUsername(), user.getRole());
LoginResponse response = new LoginResponse(); LoginResponse response = new LoginResponse();
@@ -53,9 +81,23 @@ public class AuthServiceImpl implements AuthService {
response.setRealName(user.getRealName()); response.setRealName(user.getRealName());
response.setRole(user.getRole()); response.setRole(user.getRole());
response.setOrgName(user.getOrgName()); response.setOrgName(user.getOrgName());
response.setMenus(menusOf(user));
return response; return response;
} }
@Override
public List<String> currentMenus() {
Long userId = UserContext.currentUserId();
if (userId == null) {
throw new BusinessException("未登录");
}
SysUser user = sysUserMapper.selectById(userId);
if (user == null) {
throw new BusinessException("未登录");
}
return menusOf(user);
}
@Override @Override
public SysUser currentUser() { public SysUser currentUser() {
Long userId = UserContext.currentUserId(); Long userId = UserContext.currentUserId();
@@ -68,4 +110,59 @@ public class AuthServiceImpl implements AuthService {
} }
return user; return user;
} }
private List<String> menusOf(SysUser user) {
if (isAdmin(user)) {
return new ArrayList<>(NavMenus.CODES);
}
if (user.getRoleId() == null) {
return new ArrayList<>(NavMenus.CODES);
}
try {
return roleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, user.getRoleId()))
.stream()
.map(SysRoleMenu::getMenuCode)
.filter(NavMenus::contains)
.distinct()
.toList();
} catch (Exception e) {
log.warn("读取导航权限失败,暂时开放全部栏目:{}", e.getMessage());
return new ArrayList<>(NavMenus.CODES);
}
}
private boolean isAdmin(SysUser user) {
if (user.getRole() != null && "ADMIN".equalsIgnoreCase(user.getRole())) {
return true;
}
if (user.getRoleId() == null) {
return false;
}
SysRole role = sysRoleMapper.selectById(user.getRoleId());
return role != null && "ADMIN".equalsIgnoreCase(role.getCode());
}
/** 从请求上下文取当前 HttpServletRequest(非 Web 请求线程下为 null)。 */
private HttpServletRequest currentRequest() {
try {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attrs == null ? null : attrs.getRequest();
} catch (Exception e) {
return null;
}
}
/** 取真实客户端 IP,兼容反向代理的 X-Forwarded-For。 */
private String clientIp(HttpServletRequest request) {
String forwarded = request.getHeader("X-Forwarded-For");
if (StrUtil.isNotBlank(forwarded)) {
// X-Forwarded-For 格式:client, proxy1, proxy2
return StrUtil.subPre(forwarded.trim(), forwarded.indexOf(',') < 0 ? forwarded.length() : forwarded.indexOf(',')).trim();
}
String realIp = request.getHeader("X-Real-IP");
if (StrUtil.isNotBlank(realIp)) {
return realIp.trim();
}
return request.getRemoteAddr();
}
} }
@@ -0,0 +1,260 @@
package com.banben.modules.auth.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.banben.common.PageResult;
import com.banben.modules.auth.dto.LoginLogQuery;
import com.banben.modules.auth.entity.LoginLog;
import com.banben.modules.auth.mapper.LoginLogMapper;
import com.banben.modules.auth.service.LoginLogService;
import com.banben.modules.auth.vo.AccessDimensionItem;
import com.banben.modules.auth.vo.AccessOverview;
import com.banben.modules.auth.vo.AccessTrendPoint;
import com.banben.modules.auth.vo.LoginLogSummary;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 用户登录日志服务实现。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class LoginLogServiceImpl implements LoginLogService {
private final LoginLogMapper logMapper;
@Override
public void recordLogin(Long userId, String username, String realName, String orgName, String ip, String userAgent) {
try {
LoginLog entity = new LoginLog();
entity.setUserId(userId);
entity.setUsername(username);
entity.setRealName(realName);
entity.setOrgName(orgName);
entity.setIp(ip);
entity.setUserAgent(userAgent == null ? null : StrUtil.subPre(userAgent, 500));
entity.setLoginTime(LocalDateTime.now());
entity.setOnline(1);
logMapper.insert(entity);
} catch (Exception e) {
// 日志写入失败不应影响登录主流程
log.warn("记录登录日志失败(不影响登录):{}", e.getMessage());
}
}
@Override
public void recordLogout(Long userId) {
if (userId == null) {
return;
}
try {
LoginLog entity = new LoginLog();
entity.setLogoutTime(LocalDateTime.now());
entity.setOnline(0);
// 仅关闭该用户最近一条尚未退出的会话
logMapper.update(entity, new QueryWrapper<LoginLog>()
.eq("user_id", userId)
.isNull("logout_time")
.orderByDesc("login_time")
.last("LIMIT 1"));
} catch (Exception e) {
log.warn("记录退出日志失败:{}", e.getMessage());
}
}
@Override
public PageResult<LoginLog> page(LoginLogQuery q) {
long current = q.getCurrent() == null ? 1L : q.getCurrent();
long size = q.getSize() == null ? 20L : q.getSize();
try {
QueryWrapper<LoginLog> w = new QueryWrapper<>();
if (StrUtil.isNotBlank(q.getKeyword())) {
String kw = q.getKeyword().trim();
w.and(x -> x.like("username", kw).or().like("real_name", kw).or().like("org_name", kw));
}
if ("ONLINE".equalsIgnoreCase(q.getStatus())) {
w.eq("online", 1).isNull("logout_time");
} else if ("OFFLINE".equalsIgnoreCase(q.getStatus())) {
w.isNotNull("logout_time");
}
if (StrUtil.isNotBlank(q.getLoginStart())) {
w.ge("login_time", q.getLoginStart().trim());
}
if (StrUtil.isNotBlank(q.getLoginEnd())) {
// 结束日期按当天 23:59:59 包含整日,避免漏掉结束日当天的记录
String end = q.getLoginEnd().trim();
if (end.length() == 10) {
end = end + " 23:59:59";
}
w.le("login_time", end);
}
w.orderByDesc("login_time");
Page<LoginLog> page = logMapper.selectPage(Page.of(current, size), w);
return PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
} catch (Exception e) {
// 表缺失等异常时降级为空结果,避免进入后台管理时整页报「操作失败」
log.warn("分页查询登录日志失败:{}", e.getMessage());
return PageResult.of(new ArrayList<>(), 0L, current, size);
}
}
@Override
public LoginLogSummary summary() {
LoginLogSummary s = new LoginLogSummary();
try {
s.setTotal(logMapper.selectCount(new QueryWrapper<>()));
s.setOnline(logMapper.selectCount(new QueryWrapper<LoginLog>().eq("online", 1).isNull("logout_time")));
LocalDateTime startOfToday = LocalDate.now().atStartOfDay();
s.setToday(logMapper.selectCount(new QueryWrapper<LoginLog>().ge("login_time", startOfToday)));
} catch (Exception e) {
log.warn("统计登录日志概览失败:{}", e.getMessage());
}
return s;
}
// ==================== 网络访问统计 ====================
@Override
public AccessOverview accessOverview() {
AccessOverview o = new AccessOverview();
try {
long[] history = countPair(null);
o.setHistoryCount(history[0]);
o.setHistoryUsers(history[1]);
long[] month = countPair(LocalDate.now().withDayOfMonth(1).atStartOfDay());
o.setMonthCount(month[0]);
o.setMonthUsers(month[1]);
long[] week = countPair(LocalDate.now().with(DayOfWeek.MONDAY).atStartOfDay());
o.setWeekCount(week[0]);
o.setWeekUsers(week[1]);
long[] today = countPair(LocalDate.now().atStartOfDay());
o.setTodayCount(today[0]);
o.setTodayUsers(today[1]);
} catch (Exception e) {
log.warn("统计网络访问概览失败:{}", e.getMessage());
}
return o;
}
@Override
public List<AccessTrendPoint> accessTrend(String granularity, String start, String end) {
String expr = granularityExpr(granularity);
QueryWrapper<LoginLog> w = new QueryWrapper<>();
w.select(expr + " AS bucket", "COUNT(*) AS cnt", "COUNT(DISTINCT user_id) AS users");
applyRange(w, start, end);
w.groupBy(expr).orderByAsc("bucket");
List<AccessTrendPoint> list = new ArrayList<>();
try {
for (Map<String, Object> m : logMapper.selectMaps(w)) {
Object b = m.get("bucket");
list.add(new AccessTrendPoint(b == null ? "" : b.toString(),
toLong(m.get("cnt")), toLong(m.get("users"))));
}
} catch (Exception e) {
log.warn("统计网络访问趋势失败:{}", e.getMessage());
}
return list;
}
@Override
public List<AccessDimensionItem> accessDimension(String dimension, String start, String end, int limit) {
String col = "ip";
if ("org".equals(dimension)) {
col = "org_name";
} else if ("account".equals(dimension)) {
col = "username";
} else if ("type".equals(dimension)) {
col = "online";
}
QueryWrapper<LoginLog> w = new QueryWrapper<>();
w.select(col + " AS name", "COUNT(*) AS cnt", "COUNT(DISTINCT user_id) AS users");
// 字符串维度排除空值;type 维度(online 为整数)仅排除 NULL,避免 integer <> '' 报错
if ("type".equals(dimension)) {
w.isNotNull(col);
} else {
w.isNotNull(col).ne(col, "");
}
applyRange(w, start, end);
w.groupBy(col).orderByDesc("cnt").last("LIMIT " + Math.max(1, limit));
List<AccessDimensionItem> list = new ArrayList<>();
try {
for (Map<String, Object> m : logMapper.selectMaps(w)) {
Object raw = m.get("name");
String name = raw == null ? "未知" : raw.toString();
if ("type".equals(dimension)) {
name = "1".equals(name) ? "在线" : "0".equals(name) ? "离线" : name;
}
list.add(new AccessDimensionItem(name, toLong(m.get("cnt")), toLong(m.get("users"))));
}
} catch (Exception e) {
log.warn("统计网络访问维度失败:{}", e.getMessage());
}
return list;
}
/** 人次 + 去重人数(按给定起始时间)。 */
private long[] countPair(LocalDateTime ge) {
QueryWrapper<LoginLog> w = new QueryWrapper<>();
w.select("COUNT(*) AS c", "COUNT(DISTINCT user_id) AS u");
if (ge != null) {
w.ge("login_time", ge);
}
List<Map<String, Object>> maps = logMapper.selectMaps(w);
long c = 0, u = 0;
if (!maps.isEmpty()) {
Map<String, Object> m = maps.get(0);
c = toLong(m.get("c"));
u = toLong(m.get("u"));
}
return new long[]{c, u};
}
/** 时间分桶表达式(PostgreSQL)。 */
private String granularityExpr(String g) {
if ("day".equals(g)) {
return "to_char(login_time, 'YYYY-MM-DD')";
}
if ("week".equals(g)) {
return "to_char(date_trunc('week', login_time), 'YYYY-MM-DD')";
}
if ("month".equals(g)) {
return "to_char(login_time, 'YYYY-MM')";
}
if ("year".equals(g)) {
return "to_char(login_time, 'YYYY')";
}
// 默认按小时(含日期,避免跨天合并)
return "to_char(login_time, 'YYYY-MM-DD HH24')";
}
/** 时间区间条件:start 含当天 00:00,end 含当天 23:59:59。 */
private void applyRange(QueryWrapper<LoginLog> w, String start, String end) {
if (StrUtil.isNotBlank(start)) {
w.ge("login_time", start.trim());
}
if (StrUtil.isNotBlank(end)) {
String e = end.trim();
if (e.length() == 10) {
e = e + " 23:59:59";
}
w.le("login_time", e);
}
}
private long toLong(Object value) {
return value instanceof Number number ? number.longValue() : 0L;
}
}
@@ -0,0 +1,30 @@
package com.banben.modules.auth.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 网络访问维度统计项(按 IP / 单位 / 账号 / 类型)。
*/
@Data
@Schema(description = "网络访问维度统计项")
public class AccessDimensionItem {
@Schema(description = "维度值(IP / 单位 / 账号 / 在线状态)")
private String name;
@Schema(description = "访问人次")
private long count;
@Schema(description = "访问人数(去重)")
private long users;
public AccessDimensionItem() {
}
public AccessDimensionItem(String name, long count, long users) {
this.name = name;
this.count = count;
this.users = users;
}
}
@@ -0,0 +1,38 @@
package com.banben.modules.auth.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 网络访问统计概览。
*
* <p>人次 = 登录会话记录数;人数 = 去重用户数(按 user_id)。</p>
*/
@Data
@Schema(description = "网络访问统计概览")
public class AccessOverview {
@Schema(description = "历史访问人次")
private long historyCount;
@Schema(description = "历史访问人数(去重)")
private long historyUsers;
@Schema(description = "本月访问人次")
private long monthCount;
@Schema(description = "本月访问人数(去重)")
private long monthUsers;
@Schema(description = "本周访问人次")
private long weekCount;
@Schema(description = "本周访问人数(去重)")
private long weekUsers;
@Schema(description = "今日访问人次")
private long todayCount;
@Schema(description = "今日访问人数(去重)")
private long todayUsers;
}
@@ -0,0 +1,30 @@
package com.banben.modules.auth.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 网络访问趋势(按时间分桶)。
*/
@Data
@Schema(description = "网络访问趋势(按时间分桶)")
public class AccessTrendPoint {
@Schema(description = "时间桶,如 2026-11-04 08 / 2026-11 / 2026")
private String bucket;
@Schema(description = "访问人次")
private long count;
@Schema(description = "访问人数(去重)")
private long users;
public AccessTrendPoint() {
}
public AccessTrendPoint(String bucket, long count, long users) {
this.bucket = bucket;
this.count = count;
this.users = users;
}
}
@@ -0,0 +1,21 @@
package com.banben.modules.auth.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 登录日志概览统计。
*/
@Data
@Schema(description = "登录日志概览统计")
public class LoginLogSummary {
@Schema(description = "会话总数")
private long total;
@Schema(description = "当前在线人数(未退出的会话数)")
private long online;
@Schema(description = "今日登录次数")
private long today;
}
@@ -78,6 +78,30 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
private static final int BATCH = 500; private static final int BATCH = 500;
/** 不超过该行数时,提示和提纯仍在内存里做题名包含等细查。超过后改走数据库聚合,避免整表进堆。 */
private static final int FULL_SCAN_MAX = 20000;
/** 清单返回给页面的上限。条数仍按全库统计。 */
private static final int HINT_LIST_LIMIT = 200;
/**
* 与 {@link #defectsOf} 一致的错漏条件。只在超过 {@link #FULL_SCAN_MAX} 时使用,
* 用来计数和打标,不再把整表装进内存。
*/
private static final String DEFECT_SQL = """
(btrim(coalesce(clc_code, '')) = ''
OR btrim(coalesce(keywords, '')) = ''
OR char_length(btrim(coalesce(summary, ''))) < 100
OR btrim(coalesce(publish_year, '')) !~ '^[0-9]{4}$'
OR btrim(coalesce(media_type, '')) NOT IN ('纸质', '电子')
OR btrim(coalesce(language, '')) !~ '^[A-Za-z]{3}$'
OR btrim(coalesce(page_count, '')) !~ '^[0-9]+$'
OR btrim(coalesce(author, '')) = ''
OR btrim(coalesce(fulltext_url, '')) = ''
OR btrim(coalesce(source_library, '')) = ''
OR (btrim(coalesce(isbn, '')) <> '' AND btrim(isbn) !~ '^97[89](-[0-9]+){4}$'))
""";
private final VersionResourceMapper resourceMapper; private final VersionResourceMapper resourceMapper;
@Override @Override
@@ -117,9 +141,14 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
try { try {
vo = buildHints(true); vo = buildHints(true);
job.setAffectedCount(vo.getDuplicateGroupCount() + vo.getDefectCount()); job.setAffectedCount(vo.getDuplicateGroupCount() + vo.getDefectCount());
job.setResultSummary(String.format( String summary = String.format(
"疑似同一文献 %d 组;疑似元数据错漏 %d 条(错漏记录已标记,请人工核验)", "疑似同一文献 %d 组;疑似元数据错漏 %d 条(错漏记录已标记,请人工核验)",
vo.getDuplicateGroupCount(), vo.getDefectCount())); vo.getDuplicateGroupCount(), vo.getDefectCount());
if (vo.getDuplicateGroups().size() < vo.getDuplicateGroupCount()
|| vo.getDefects().size() < vo.getDefectCount()) {
summary += "。清单过长,页面只展示前 " + HINT_LIST_LIMIT + " 条";
}
job.setResultSummary(summary);
job.setStatus("SUCCESS"); job.setStatus("SUCCESS");
vo.setJob(job); vo.setJob(job);
} catch (Exception e) { } catch (Exception e) {
@@ -428,6 +457,9 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
* 疑似错漏:必备要素缺失、摘要不足 100 字、年份/语种/页码/ISBN 格式不正确。 * 疑似错漏:必备要素缺失、摘要不足 100 字、年份/语种/页码/ISBN 格式不正确。
*/ */
private GovernanceHintVO buildHints(boolean persistFlag) { private GovernanceHintVO buildHints(boolean persistFlag) {
if (countActive() > FULL_SCAN_MAX) {
return buildHintsForLargeTable(persistFlag);
}
List<VersionResource> active = loadActive(); List<VersionResource> active = loadActive();
GovernanceHintVO vo = new GovernanceHintVO(); GovernanceHintVO vo = new GovernanceHintVO();
vo.setDuplicateGroups(findSuspectedDuplicates(active)); vo.setDuplicateGroups(findSuspectedDuplicates(active));
@@ -454,6 +486,103 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
return vo; return vo;
} }
/**
* 大表不再整表读入。疑似重复只按 ISBN、或无 ISBN 时的书名+作者+出版社+出版年份在库里聚合;
* 题名互相包含这类细查只在 {@link #FULL_SCAN_MAX} 以内做。错漏用 {@link #DEFECT_SQL} 计数和打标,
* 页面只带回前 {@link #HINT_LIST_LIMIT} 条。
*/
private GovernanceHintVO buildHintsForLargeTable(boolean persistFlag) {
GovernanceHintVO vo = new GovernanceHintVO();
List<DuplicateGroupVO> groups = new ArrayList<>();
vo.setDuplicateGroupCount(appendExactDuplicateGroups(groups, HINT_LIST_LIMIT));
vo.setDuplicateGroups(groups);
long defectCount = countDefects();
vo.setDefectCount(defectCount > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) defectCount);
vo.setDefects(sampleDefects(HINT_LIST_LIMIT));
if (persistFlag) {
markDefectsBySql();
}
return vo;
}
private int appendExactDuplicateGroups(List<DuplicateGroupVO> groups, int limit) {
int count = 0;
for (Map<String, Object> group : isbnDuplicateGroups()) {
count++;
if (groups.size() >= limit) {
continue;
}
Object isbn = group.get("isbn");
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.eq(VersionResource::getIsbn, isbn)
.and(this::notMergedOut)
.orderByAsc(VersionResource::getId);
groups.add(toDuplicateGroup("ISBN 相同,疑似同一文献", String.valueOf(isbn), resourceMapper.selectList(query)));
}
for (Map<String, Object> group : fieldDuplicateGroups()) {
count++;
if (groups.size() >= limit) {
continue;
}
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.eq(VersionResource::getTitle, group.get("title"));
eqOrIsNull(query, VersionResource::getAuthor, group.get("author"));
eqOrIsNull(query, VersionResource::getPublisher, group.get("publisher"));
eqOrIsNull(query, VersionResource::getPublishYear, group.get("publish_year"));
query.and(x -> x.isNull(VersionResource::getIsbn).or().eq(VersionResource::getIsbn, ""))
.and(this::notMergedOut)
.orderByAsc(VersionResource::getId);
String key = text(group.get("title") == null ? null : String.valueOf(group.get("title")));
groups.add(toDuplicateGroup("书名、责任者、出版社、出版年份一致,疑似同一文献", key, resourceMapper.selectList(query)));
}
return count;
}
private long countDefects() {
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.and(this::notMergedOut).apply(DEFECT_SQL);
Long count = resourceMapper.selectCount(query);
return count == null ? 0 : count;
}
private List<DefectItemVO> sampleDefects(int limit) {
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.and(this::notMergedOut)
.apply(DEFECT_SQL)
.orderByAsc(VersionResource::getId)
.last("LIMIT " + limit);
List<DefectItemVO> defects = new ArrayList<>();
for (VersionResource resource : resourceMapper.selectList(query)) {
List<String> issues = defectsOf(resource);
if (!issues.isEmpty()) {
defects.add(toDefect(resource, issues));
}
}
return defects;
}
private void markDefectsBySql() {
LambdaUpdateWrapper<VersionResource> mark = new LambdaUpdateWrapper<>();
mark.set(VersionResource::getAbnormalFlag, 1)
.and(this::notMergedOutUpdate)
.apply(DEFECT_SQL);
resourceMapper.update(null, mark);
LambdaUpdateWrapper<VersionResource> clear = new LambdaUpdateWrapper<>();
clear.set(VersionResource::getAbnormalFlag, 0)
.eq(VersionResource::getAbnormalFlag, 1)
.and(this::notMergedOutUpdate)
.apply("NOT (" + DEFECT_SQL + ")");
resourceMapper.update(null, clear);
}
private void notMergedOutUpdate(LambdaUpdateWrapper<VersionResource> query) {
query.isNull(VersionResource::getGovernStatus)
.or()
.ne(VersionResource::getGovernStatus, GovernStatus.MERGED_OUT.getCode());
}
private List<DuplicateGroupVO> findSuspectedDuplicates(List<VersionResource> active) { private List<DuplicateGroupVO> findSuspectedDuplicates(List<VersionResource> active) {
List<DuplicateGroupVO> groups = new ArrayList<>(); List<DuplicateGroupVO> groups = new ArrayList<>();
Set<Long> emitted = new HashSet<>(); Set<Long> emitted = new HashSet<>();
@@ -606,6 +735,10 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
* 尚未聚同的重复文献、已聚同但还没优化的主记录、仍有错漏的记录。 * 尚未聚同的重复文献、已聚同但还没优化的主记录、仍有错漏的记录。
*/ */
private void runPurify(GovernanceJob job) { private void runPurify(GovernanceJob job) {
if (countActive() > FULL_SCAN_MAX) {
runPurifyInBatches(job);
return;
}
List<VersionResource> active = loadActive(); List<VersionResource> active = loadActive();
Set<Long> unresolved = unresolvedDuplicateIds(active); Set<Long> unresolved = unresolvedDuplicateIds(active);
@@ -691,6 +824,108 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
// ==================== 公共方法 ==================== // ==================== 公共方法 ====================
private void runPurifyInBatches(GovernanceJob job) {
Set<Long> unresolved = duplicateIdsBySql();
int nonBook = 0;
int sensitive = 0;
int blocked = 0;
int duplicated = 0;
int waitOptimize = 0;
int defect = 0;
List<Long> accepted = new ArrayList<>();
long lastId = 0;
while (true) {
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.and(this::notMergedOut)
.gt(VersionResource::getId, lastId)
.orderByAsc(VersionResource::getId)
.last("LIMIT " + BATCH);
List<VersionResource> batch = resourceMapper.selectList(query);
if (batch.isEmpty()) {
break;
}
lastId = batch.get(batch.size() - 1).getId();
for (VersionResource resource : batch) {
if (GovernStatus.FINAL.getCode().equals(resource.getGovernStatus())) {
continue;
}
if (!paperElectronicBook(resource)) {
nonBook++;
continue;
}
if (resource.getSensitiveFlag() != null && resource.getSensitiveFlag() == 1) {
sensitive++;
continue;
}
if (resource.getManageStatus() != null && resource.getManageStatus() != 0) {
blocked++;
continue;
}
if (unresolved.contains(resource.getId())) {
duplicated++;
continue;
}
if (GovernStatus.MERGED.getCode().equals(resource.getGovernStatus())) {
waitOptimize++;
continue;
}
if (!defectsOf(resource).isEmpty()) {
defect++;
continue;
}
accepted.add(resource.getId());
}
}
updateStatus(accepted, GovernStatus.FINAL.getCode());
job.setAffectedCount(accepted.size());
job.setResultSummary(String.format(
"已将 %d 条纸电图书纳入版本资源数据集。"
+ "未纳入:非纸电图书 %d 条,敏感 %d 条,已屏蔽或下架 %d 条,"
+ "尚未聚同的重复文献 %d 条,已聚同但未优化 %d 条,仍有错漏 %d 条",
accepted.size(), nonBook, sensitive, blocked, duplicated, waitOptimize, defect));
}
private Set<Long> duplicateIdsBySql() {
Set<Long> ids = new HashSet<>();
QueryWrapper<VersionResource> byIsbn = new QueryWrapper<>();
byIsbn.select("id")
.apply("btrim(coalesce(isbn, '')) <> ''")
.and(w -> w.isNull("govern_status").or().ne("govern_status", GovernStatus.MERGED_OUT.getCode()))
.inSql("isbn", "SELECT isbn FROM version_resource WHERE deleted = 0 "
+ "AND (govern_status IS NULL OR govern_status <> 'MERGED_OUT') "
+ "AND btrim(coalesce(isbn, '')) <> '' "
+ "GROUP BY isbn HAVING COUNT(*) > 1");
collectIds(ids, resourceMapper.selectMaps(byIsbn));
QueryWrapper<VersionResource> byField = new QueryWrapper<>();
byField.select("id")
.apply("btrim(coalesce(isbn, '')) = ''")
.and(w -> w.isNull("govern_status").or().ne("govern_status", GovernStatus.MERGED_OUT.getCode()))
.apply("(title, author, publisher, publish_year) IN ("
+ "SELECT title, author, publisher, publish_year FROM version_resource "
+ "WHERE deleted = 0 AND (govern_status IS NULL OR govern_status <> 'MERGED_OUT') "
+ "AND btrim(coalesce(isbn, '')) = '' AND title IS NOT NULL "
+ "GROUP BY title, author, publisher, publish_year HAVING COUNT(*) > 1)");
collectIds(ids, resourceMapper.selectMaps(byField));
return ids;
}
private void collectIds(Set<Long> ids, List<Map<String, Object>> rows) {
for (Map<String, Object> row : rows) {
Object id = row.get("id");
if (id instanceof Number number) {
ids.add(number.longValue());
}
}
}
private long countActive() {
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.and(this::notMergedOut);
Long count = resourceMapper.selectCount(query);
return count == null ? 0 : count;
}
private List<VersionResource> loadActive() { private List<VersionResource> loadActive() {
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>(); LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.and(this::notMergedOut).orderByAsc(VersionResource::getId); query.and(this::notMergedOut).orderByAsc(VersionResource::getId);
@@ -0,0 +1,74 @@
package com.banben.modules.resource.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.banben.common.Result;
import com.banben.modules.resource.entity.ResourceSource;
import com.banben.modules.resource.mapper.ResourceSourceMapper;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.mapper.VersionResourceMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
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.RestController;
import java.util.List;
/**
* 版本资源多来源管理接口。
*
* <p>对应检索概览页「一条结果可有多个来源,点击可下载」的能力:
* 一条文献可挂载到多个资源库 / 来源馆,概览页据此渲染多个来源并分别下载。</p>
*/
@Tag(name = "版本资源-多来源管理", description = "文献多来源(资源库)的增删改查")
@RestController
@RequestMapping("/api/resource")
@RequiredArgsConstructor
public class ResourceSourceController {
private final ResourceSourceMapper sourceMapper;
private final VersionResourceMapper resourceMapper;
@Operation(summary = "查询某条文献的全部来源(按展示顺序)")
@GetMapping("/{id}/sources")
public Result<List<ResourceSource>> list(@PathVariable Long id) {
QueryWrapper<ResourceSource> w = new QueryWrapper<>();
w.eq("resource_id", id).eq("deleted", 0).orderByAsc("sort_no");
return Result.success(sourceMapper.selectList(w));
}
@Operation(summary = "为某条文献新增一个来源")
@PostMapping("/{id}/sources")
public Result<Long> add(@PathVariable Long id, @RequestBody ResourceSource source) {
VersionResource r = resourceMapper.selectById(id);
if (r == null) {
return Result.failed("文献不存在:" + id);
}
source.setId(null);
source.setResourceId(id);
sourceMapper.insert(source);
return Result.success(source.getId());
}
@Operation(summary = "更新某个来源")
@PutMapping("/sources/{sourceId}")
public Result<Void> update(@PathVariable Long sourceId, @RequestBody ResourceSource source) {
source.setId(sourceId);
source.setResourceId(null); // 不允许跨文献改归属
sourceMapper.updateById(source);
return Result.success();
}
@Operation(summary = "删除某个来源(逻辑删除)")
@DeleteMapping("/sources/{sourceId}")
public Result<Void> remove(@PathVariable Long sourceId) {
sourceMapper.deleteById(sourceId);
return Result.success();
}
}
@@ -0,0 +1,66 @@
package com.banben.modules.resource.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;
/**
* 版本资源多来源(一条文献可来自多个资源库 / 来源馆)。
*
* <p>对应招标文件检索结果概览页要求:「一条结果可有多个来源,按资源库图标+名称展示,点击可下载」。
* 主表 {@link VersionResource} 上的 source_library / source_repo / fulltext_url 等字段作为
* 「主来源」兜底;本表保存该文献的全部来源,概览页据此渲染多个可分别下载的来源。</p>
*/
@Data
@TableName("resource_source")
@Schema(description = "版本资源多来源")
public class ResourceSource implements Serializable {
@TableId(type = IdType.AUTO)
@Schema(description = "来源记录主键")
private Long id;
@Schema(description = "关联版本资源主记录ID(version_resource.id)")
private Long resourceId;
@Schema(description = "来源资源库名")
private String sourceRepo;
@Schema(description = "来源馆")
private String sourceLibrary;
@Schema(description = "来源馆地址(IP:端口或域名)")
private String sourceLibraryAddr;
@Schema(description = "全文地址(下载地址)")
private String fulltextUrl;
@Schema(description = "加工编号(该来源库内的编号)")
private String processNo;
@Schema(description = "媒体类型(纸质/电子,可选,便于概览页区分)")
private String mediaType;
@Schema(description = "展示顺序,数值小的靠前")
private Integer sortNo;
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建时间")
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
@Schema(description = "更新时间")
private LocalDateTime updateTime;
@TableLogic
@Schema(description = "逻辑删除:0未删 1已删")
private Integer deleted;
}
@@ -153,9 +153,17 @@ public class VersionResource implements Serializable {
@Schema(description = "作者单位(责任者所属机构)") @Schema(description = "作者单位(责任者所属机构)")
private String authorOrg; private String authorOrg;
@Schema(description = "来源资源库名") @Schema(description = "来源资源库名(主来源兜底,多来源详见 sources)")
private String sourceRepo; private String sourceRepo;
/**
* 多来源列表(一条文献可来自多个资源库)。
* 非数据库字段,由检索/细览接口按 resource_id 批量挂载,供概览页按来源展示并分别下载。
*/
@TableField(exist = false)
@Schema(description = "多来源列表:一条文献可来自多个资源库,概览页按来源图标+名称展示并可分别下载")
private java.util.List<ResourceSource> sources;
@TableField(fill = FieldFill.INSERT) @TableField(fill = FieldFill.INSERT)
@Schema(description = "创建时间") @Schema(description = "创建时间")
private LocalDateTime createTime; private LocalDateTime createTime;
@@ -0,0 +1,12 @@
package com.banben.modules.resource.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.resource.entity.ResourceSource;
import org.apache.ibatis.annotations.Mapper;
/**
* 版本资源多来源 Mapper。
*/
@Mapper
public interface ResourceSourceMapper extends BaseMapper<ResourceSource> {
}
@@ -29,8 +29,8 @@ public class VersionResourceExcelService {
private final VersionResourceService versionResourceService; private final VersionResourceService versionResourceService;
/** 单次导入的最大数据行数,防止超大文件拖垮服务 */ /** 下拉校验覆盖的行数;只影响模板中下拉框的作用范围,不限制导入行数 */
private static final int MAX_ROWS = 5000; private static final int DROPDOWN_ROWS = 5000;
private record Column(String header, String field, private record Column(String header, String field,
BiConsumer<VersionResource, String> setter, int maxLen, String hint) { BiConsumer<VersionResource, String> setter, int maxLen, String hint) {
@@ -215,7 +215,7 @@ public class VersionResourceExcelService {
DataValidationHelper helper = sheet.getDataValidationHelper(); DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = DataValidationConstraint constraint =
helper.createExplicitListConstraint(options); helper.createExplicitListConstraint(options);
CellRangeAddressList range = new CellRangeAddressList(2, MAX_ROWS, colIndex, colIndex); CellRangeAddressList range = new CellRangeAddressList(2, DROPDOWN_ROWS, colIndex, colIndex);
DataValidation validation = helper.createValidation(constraint, range); DataValidation validation = helper.createValidation(constraint, range);
validation.setSuppressDropDownArrow(true); validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true); validation.setShowErrorBox(true);
@@ -267,7 +267,7 @@ public class VersionResourceExcelService {
List<VersionResource> parsed = new ArrayList<>(); List<VersionResource> parsed = new ArrayList<>();
List<Integer> rowNums = new ArrayList<>(); List<Integer> rowNums = new ArrayList<>();
int last = Math.min(sheet.getLastRowNum(), startRow + MAX_ROWS); int last = sheet.getLastRowNum();
for (int r = startRow; r <= last; r++) { for (int r = startRow; r <= last; r++) {
Row row = sheet.getRow(r); Row row = sheet.getRow(r);
if (row == null) continue; if (row == null) continue;
@@ -24,6 +24,9 @@ public class SearchQuery {
@Schema(description = "综合关键词(题名/作者/关键词/摘要/出版者 模糊匹配)") @Schema(description = "综合关键词(题名/作者/关键词/摘要/出版者 模糊匹配)")
private String keyword; private String keyword;
@Schema(description = "去除关键字(结果集排除,空格分隔可多个;含任一排除词的记录不返回)")
private String excludeKeyword;
@Schema(description = "题名") @Schema(description = "题名")
private String title; private String title;
@@ -49,6 +52,9 @@ public class SearchQuery {
@Schema(description = "媒体类型:纸质/电子") @Schema(description = "媒体类型:纸质/电子")
private String mediaType; private String mediaType;
@Schema(description = "媒体类型(多选,in):纸质/电子")
private List<String> mediaTypes;
@Schema(description = "语种分组:chi 中文文献 / foreign 外文文献(首页前置筛选用)") @Schema(description = "语种分组:chi 中文文献 / foreign 外文文献(首页前置筛选用)")
private String languageGroup; private String languageGroup;
@@ -58,6 +64,9 @@ public class SearchQuery {
@Schema(description = "来源馆(单选,左侧「来源院校」分面点选用)") @Schema(description = "来源馆(单选,左侧「来源院校」分面点选用)")
private String sourceLibrary; private String sourceLibrary;
@Schema(description = "来源资源库名(多选,in)")
private List<String> sourceRepos;
/** ---------------- 限定出版时段 ---------------- */ /** ---------------- 限定出版时段 ---------------- */
@Schema(description = "出版年份起(含)", example = "2000") @Schema(description = "出版年份起(含)", example = "2000")
private String publishYearStart; private String publishYearStart;
@@ -69,6 +78,9 @@ public class SearchQuery {
@Schema(description = "匹配精度:EQ 精确 / LEFT 前方一致 / RIGHT 后方一致 / LIKE 模糊(默认)") @Schema(description = "匹配精度:EQ 精确 / LEFT 前方一致 / RIGHT 后方一致 / LIKE 模糊(默认)")
private String matchType = "LIKE"; private String matchType = "LIKE";
@Schema(description = "在结果中搜索:新增关键词必须同时命中(AND 收窄当前结果集)")
private String withinKeyword;
@Schema(description = "多字段逻辑:AND(默认) / OR") @Schema(description = "多字段逻辑:AND(默认) / OR")
private String logic = "AND"; private String logic = "AND";
@@ -7,7 +7,9 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.banben.common.PageResult; import com.banben.common.PageResult;
import com.banben.modules.admin.entity.SensitiveWord; import com.banben.modules.admin.entity.SensitiveWord;
import com.banben.modules.admin.mapper.SensitiveWordMapper; import com.banben.modules.admin.mapper.SensitiveWordMapper;
import com.banben.modules.resource.entity.ResourceSource;
import com.banben.modules.resource.entity.VersionResource; import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.mapper.ResourceSourceMapper;
import com.banben.modules.resource.mapper.VersionResourceMapper; import com.banben.modules.resource.mapper.VersionResourceMapper;
import com.banben.modules.search.dto.SearchQuery; import com.banben.modules.search.dto.SearchQuery;
import com.banben.modules.search.entity.ClcCategory; import com.banben.modules.search.entity.ClcCategory;
@@ -26,8 +28,11 @@ import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/** /**
* 检索发现服务实现。 * 检索发现服务实现。
@@ -45,6 +50,7 @@ public class SearchServiceImpl implements SearchService {
private static final int FACET_TOP = 20; private static final int FACET_TOP = 20;
private final VersionResourceMapper resourceMapper; private final VersionResourceMapper resourceMapper;
private final ResourceSourceMapper sourceMapper;
private final SearchLogMapper searchLogMapper; private final SearchLogMapper searchLogMapper;
private final ClcCategoryMapper clcCategoryMapper; private final ClcCategoryMapper clcCategoryMapper;
private final SensitiveWordMapper sensitiveWordMapper; private final SensitiveWordMapper sensitiveWordMapper;
@@ -74,6 +80,7 @@ public class SearchServiceImpl implements SearchService {
Page.of(query.getCurrent(), query.getSize()), wrapper); Page.of(query.getCurrent(), query.getSize()), wrapper);
SearchResultVO vo = new SearchResultVO(); SearchResultVO vo = new SearchResultVO();
attachSources(page.getRecords());
vo.setPage(PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize())); vo.setPage(PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize()));
// 命中但被屏蔽/下架而不展示的记录数(含管理状态口径的总数 - 实际可见总数)。 // 命中但被屏蔽/下架而不展示的记录数(含管理状态口径的总数 - 实际可见总数)。
@@ -92,6 +99,7 @@ public class SearchServiceImpl implements SearchService {
vo.setMediaTypeFacets(facet(query, "media_type")); vo.setMediaTypeFacets(facet(query, "media_type"));
vo.setSourceLibraryFacets(facet(query, "source_library")); vo.setSourceLibraryFacets(facet(query, "source_library"));
vo.setSourceRepoFacets(facet(query, "source_repo"));
vo.setClcFacets(clcFacet(query)); vo.setClcFacets(clcFacet(query));
vo.setYearStats(yearStats(query)); vo.setYearStats(yearStats(query));
@@ -110,7 +118,11 @@ public class SearchServiceImpl implements SearchService {
@Override @Override
public VersionResource detail(Long id) { public VersionResource detail(Long id) {
return resourceMapper.selectById(id); VersionResource r = resourceMapper.selectById(id);
if (r != null) {
attachSources(List.of(r));
}
return r;
} }
@Override @Override
@@ -141,7 +153,9 @@ public class SearchServiceImpl implements SearchService {
}); });
} }
wrapper.orderByDesc("publish_year").last("limit " + Math.max(1, limit)); wrapper.orderByDesc("publish_year").last("limit " + Math.max(1, limit));
return resourceMapper.selectList(wrapper); List<VersionResource> list = resourceMapper.selectList(wrapper);
attachSources(list);
return list;
} }
@Override @Override
@@ -149,7 +163,51 @@ public class SearchServiceImpl implements SearchService {
QueryWrapper<VersionResource> wrapper = buildWrapper(query); QueryWrapper<VersionResource> wrapper = buildWrapper(query);
applyOrder(wrapper, query); applyOrder(wrapper, query);
wrapper.last("limit " + Math.max(1, limit)); wrapper.last("limit " + Math.max(1, limit));
return resourceMapper.selectList(wrapper); List<VersionResource> list = resourceMapper.selectList(wrapper);
attachSources(list);
return list;
}
/**
* 批量挂载多来源:按主记录 ID 一次查出全部来源,挂到各 {@link VersionResource#sources} 上。
*
* <p>来源为空(旧数据未维护多来源)时,{@code sources} 保持为空列表,
* 前端会回退到主表单来源字段展示与下载。</p>
*/
private void attachSources(List<VersionResource> records) {
if (records == null || records.isEmpty()) {
return;
}
List<Long> ids = records.stream()
.map(VersionResource::getId)
.filter(Objects::nonNull)
.distinct()
.toList();
if (ids.isEmpty()) {
return;
}
try {
List<ResourceSource> all = sourceMapper.selectList(
new QueryWrapper<ResourceSource>()
.in("resource_id", ids)
.eq("deleted", 0)
.orderByAsc("sort_no"));
Map<Long, List<ResourceSource>> byRes = all.stream()
.collect(Collectors.groupingBy(
ResourceSource::getResourceId,
LinkedHashMap::new,
Collectors.toList()));
for (VersionResource r : records) {
r.setSources(byRes.getOrDefault(r.getId(), List.of()));
}
} catch (Exception e) {
log.warn("批量挂载多来源失败(不影响主结果返回):{}", e.getMessage());
for (VersionResource r : records) {
if (r.getSources() == null) {
r.setSources(List.of());
}
}
}
} }
// ==================== 内部方法 ==================== // ==================== 内部方法 ====================
@@ -190,8 +248,11 @@ public class SearchServiceImpl implements SearchService {
|| StrUtil.isNotBlank(q.getAuthor()) || StrUtil.isNotBlank(q.getPublisher()) || StrUtil.isNotBlank(q.getAuthor()) || StrUtil.isNotBlank(q.getPublisher())
|| StrUtil.isNotBlank(q.getIsbn()) || StrUtil.isNotBlank(q.getCdoi()) || StrUtil.isNotBlank(q.getIsbn()) || StrUtil.isNotBlank(q.getCdoi())
|| StrUtil.isNotBlank(q.getClcCode()) || CollectionUtil.isNotEmpty(q.getClcCodes()) || StrUtil.isNotBlank(q.getClcCode()) || CollectionUtil.isNotEmpty(q.getClcCodes())
|| StrUtil.isNotBlank(q.getMediaType()) || StrUtil.isNotBlank(q.getLanguageGroup()) || StrUtil.isNotBlank(q.getMediaType()) || CollectionUtil.isNotEmpty(q.getMediaTypes())
|| StrUtil.isNotBlank(q.getLanguageGroup())
|| StrUtil.isNotBlank(q.getSourceLibrary()) || CollectionUtil.isNotEmpty(q.getSourceLibraries()) || StrUtil.isNotBlank(q.getSourceLibrary()) || CollectionUtil.isNotEmpty(q.getSourceLibraries())
|| CollectionUtil.isNotEmpty(q.getSourceRepos())
|| StrUtil.isNotBlank(q.getWithinKeyword())
|| StrUtil.isNotBlank(q.getPublishYearStart()) || StrUtil.isNotBlank(q.getPublishYearEnd()); || StrUtil.isNotBlank(q.getPublishYearStart()) || StrUtil.isNotBlank(q.getPublishYearEnd());
} }
@@ -233,6 +294,29 @@ public class SearchServiceImpl implements SearchService {
}); });
} }
// 去除关键字:排除含任一排除词的记录(与综合关键词覆盖同样的文本字段)
// 字段为空(IS NULL)不计入排除,避免把缺字段的记录误删
if (StrUtil.isNotBlank(q.getExcludeKeyword())) {
List<String> exTerms = splitTerms(q.getExcludeKeyword());
for (String ex : exTerms) {
w.and(x -> x
.and(y -> y.notLike("title", ex).or().isNull("title"))
.and(y -> y.notLike("author", ex).or().isNull("author"))
.and(y -> y.notLike("keywords", ex).or().isNull("keywords"))
.and(y -> y.notLike("summary", ex).or().isNull("summary"))
.and(y -> y.notLike("publisher", ex).or().isNull("publisher"))
);
}
}
// 在结果中搜索:每个新增关键词都必须命中(AND 收窄当前结果集)
if (StrUtil.isNotBlank(q.getWithinKeyword())) {
for (String kw : splitTerms(q.getWithinKeyword())) {
w.and(x -> x.nested(y -> y.like("title", kw).or().like("author", kw).or()
.like("keywords", kw).or().like("summary", kw).or().like("publisher", kw)));
}
}
applyMatch(w, "title", q.getTitle(), q.getMatchType()); applyMatch(w, "title", q.getTitle(), q.getMatchType());
applyMatch(w, "author", q.getAuthor(), q.getMatchType()); applyMatch(w, "author", q.getAuthor(), q.getMatchType());
applyMatch(w, "publisher", q.getPublisher(), q.getMatchType()); applyMatch(w, "publisher", q.getPublisher(), q.getMatchType());
@@ -240,7 +324,7 @@ public class SearchServiceImpl implements SearchService {
applyMatch(w, "cdoi", q.getCdoi(), q.getMatchType()); applyMatch(w, "cdoi", q.getCdoi(), q.getMatchType());
if (!excludeClc && StrUtil.isNotBlank(q.getClcCode())) { if (!excludeClc && StrUtil.isNotBlank(q.getClcCode())) {
w.likeRight("clc_code", q.getClcCode().trim()); w.likeRight("clc_code", q.getClcCode().trim().toUpperCase());
} }
// 中图法树导航:点部类时传入其下所有大类号,任一命中即可 // 中图法树导航:点部类时传入其下所有大类号,任一命中即可
if (!excludeClc && CollectionUtil.isNotEmpty(q.getClcCodes())) { if (!excludeClc && CollectionUtil.isNotEmpty(q.getClcCodes())) {
@@ -254,13 +338,18 @@ public class SearchServiceImpl implements SearchService {
x.or(); x.or();
} }
first = false; first = false;
x.likeRight("clc_code", c.trim()); x.likeRight("clc_code", c.trim().toUpperCase());
} }
}); });
} }
if (StrUtil.isNotBlank(q.getMediaType()) && !"media_type".equals(excludeColumn)) { // 资源类型:单选或罗列多选(分面排除时跳过本列过滤,便于切换)
if (!"media_type".equals(excludeColumn)) {
if (CollectionUtil.isNotEmpty(q.getMediaTypes())) {
w.in("media_type", q.getMediaTypes());
} else if (StrUtil.isNotBlank(q.getMediaType())) {
w.eq("media_type", q.getMediaType()); w.eq("media_type", q.getMediaType());
} }
}
// 语种分组:中文文献含 chi/zh/中文(库内有少量中文写法的脏数据); // 语种分组:中文文献含 chi/zh/中文(库内有少量中文写法的脏数据);
// 外文文献 = 不在中文集合内(NULL 语种视为未知,两侧都不计入外文组) // 外文文献 = 不在中文集合内(NULL 语种视为未知,两侧都不计入外文组)
if ("chi".equalsIgnoreCase(q.getLanguageGroup())) { if ("chi".equalsIgnoreCase(q.getLanguageGroup())) {
@@ -268,13 +357,18 @@ public class SearchServiceImpl implements SearchService {
} else if ("foreign".equalsIgnoreCase(q.getLanguageGroup())) { } else if ("foreign".equalsIgnoreCase(q.getLanguageGroup())) {
w.notIn("language", List.of("chi", "zh", "中文")); w.notIn("language", List.of("chi", "zh", "中文"));
} }
// 来源院校:多选(IN)或单选(分面排除时跳过本列过滤)
if (!"source_library".equals(excludeColumn)) {
if (CollectionUtil.isNotEmpty(q.getSourceLibraries())) { if (CollectionUtil.isNotEmpty(q.getSourceLibraries())) {
w.in("source_library", q.getSourceLibraries()); w.in("source_library", q.getSourceLibraries());
} } else if (StrUtil.isNotBlank(q.getSourceLibrary())) {
// 来源院校分面单选(前端点选传单数字段)
if (StrUtil.isNotBlank(q.getSourceLibrary()) && !"source_library".equals(excludeColumn)) {
w.eq("source_library", q.getSourceLibrary().trim()); w.eq("source_library", q.getSourceLibrary().trim());
} }
}
// 资源库名:多选(IN)
if (CollectionUtil.isNotEmpty(q.getSourceRepos()) && !"source_repo".equals(excludeColumn)) {
w.in("source_repo", q.getSourceRepos());
}
if (StrUtil.isNotBlank(q.getPublishYearStart())) { if (StrUtil.isNotBlank(q.getPublishYearStart())) {
w.ge("publish_year", q.getPublishYearStart().trim()); w.ge("publish_year", q.getPublishYearStart().trim());
} }
@@ -25,6 +25,9 @@ public class SearchResultVO {
@Schema(description = "来源院校分面") @Schema(description = "来源院校分面")
private List<FacetItem> sourceLibraryFacets; private List<FacetItem> sourceLibraryFacets;
@Schema(description = "资源库名分面")
private List<FacetItem> sourceRepoFacets;
@Schema(description = "中图分类分面") @Schema(description = "中图分类分面")
private List<FacetItem> clcFacets; private List<FacetItem> clcFacets;
@@ -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,99 @@
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)");
jdbcTemplate.execute(
"CREATE TABLE IF NOT EXISTS sync_hub_cursor ("
+ "node_code VARCHAR(32) NOT NULL PRIMARY KEY, "
+ "last_resource_id BIGINT DEFAULT 0, "
+ "update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
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,79 @@
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 = "";
/** 纸质书写入这张表,陆工大测试库是 book_attr */
private String paperTable = "book_attr";
/** 电子书写入这张表,陆工大测试库是 e_book */
private String ebookTable = "e_book";
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,163 @@
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()));
}
/**
* 总库往下推。
* 陆工大已配置 MySQL 时,从 version_resource 按批读取:纸质写入 book_attr,电子写入 e_book,已有 ISBN 的跳过。
* 一次最多新增 batch-size 条,没有推完时返回里会提示再调一次。不会一次写完总库全部图书。
*/
@Operation(summary = "总库按测试库表结构把 version_resource 分批回写到节点")
@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,64 @@
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;
/** 其他题名,下推到 book_attr.TITLE_S */
private String otherTitle;
private String author;
private String isbn;
private String publisher;
private String publishYear;
/** 出版日期,下推到 PUB_DATE */
private String publishDate;
/** 版次,下推到 book_attr.VERSION */
private String edition;
private String keywords;
private String summary;
private String clcCode;
private String mediaType;
private String language;
private String contentForm;
private String sourceLibrary;
private String fulltextUrl;
/** version_resource.id,只在总库下推时用来记住读到哪一条。 */
@JsonIgnore
private Long resourceId;
@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,252 @@
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 com.banben.modules.synchub.service.BookCleaner;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 把总库图书按陆工大测试库的表结构写回去。
* 纸质写入 book_attr,电子写入 e_book。ISBN 或题名已经存在的不再插入。
*/
@Component
@RequiredArgsConstructor
public class MysqlNodeWriter {
private final BookCleaner cleaner;
public WriteResult write(SyncHubProperties.Node node, List<BookDocument> books) {
if (node.getMysqlUrl() == null || node.getMysqlUrl().isBlank()) {
throw new BusinessException(node.getName() + " 还没配置 MySQL 地址");
}
String paper = table(node.getPaperTable(), "book_attr");
String ebook = table(node.getEbookTable(), "e_book");
int inserted = 0;
int skipped = 0;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new BusinessException("缺少 MySQL 驱动");
}
try (Connection connection = DriverManager.getConnection(node.getMysqlUrl(), node.getMysqlUser(), node.getMysqlPassword())) {
// 测试库的 book_attr.RECORD_ID 指向 bibliography,但 bibliography 和字典表是空的,
// 现有两条书也没有父记录。这里按现有数据的方式只写书目表。
try (Statement statement = connection.createStatement()) {
statement.execute("SET FOREIGN_KEY_CHECKS = 0");
}
long paperId = maxId(connection, paper);
long ebookId = maxId(connection, ebook);
Set<String> seen = new HashSet<>();
for (BookDocument book : books) {
if (book.getTitle() == null || book.getTitle().isBlank()) {
skipped++;
continue;
}
if (!seen.add(cleaner.matchKey(book))) {
skipped++;
continue;
}
boolean electronic = book.getMediaType() != null && book.getMediaType().contains("电子");
String target = electronic ? ebook : paper;
if (electronic ? existsEbook(connection, ebook, book) : existsPaper(connection, paper, book)) {
skipped++;
continue;
}
if (electronic) {
ebookId++;
insertEbook(connection, ebook, ebookId, book);
} else {
paperId++;
insertPaper(connection, paper, paperId, book);
}
inserted++;
}
try (Statement statement = connection.createStatement()) {
statement.execute("SET FOREIGN_KEY_CHECKS = 1");
}
} catch (SQLException e) {
throw new BusinessException("写入" + node.getName() + "失败:" + safe(e.getMessage(), node.getMysqlPassword()));
}
return new WriteResult(inserted, skipped);
}
private void insertPaper(Connection connection, String table, long id, BookDocument book) throws SQLException {
String isbn13 = isbn13(book.getIsbn());
String isbn10 = isbn13.length() == 10 ? isbn13 : "";
String sql = "INSERT INTO `" + table + "` (RECORD_ID, CALL_NO, TITLE, TITLE_S, ISBN13, ISBN10, ISBN, AUTHOR, PUBLISHER, PUB_DATE, PUB_YEAR, VERSION) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setLong(1, id);
ps.setString(2, cut(book.getClcCode(), 255));
ps.setString(3, cut(book.getTitle(), 1000));
ps.setString(4, cut(first(book.getOtherTitle(), book.getTitle()), 1000));
ps.setString(5, cut(isbn13, 32));
ps.setString(6, cut(isbn10, 32));
ps.setString(7, cut(book.getIsbn(), 64));
ps.setString(8, cut(book.getAuthor(), 500));
ps.setString(9, cut(book.getPublisher(), 500));
ps.setString(10, cut(book.getPublishDate(), 32));
ps.setString(11, cut(book.getPublishYear(), 16));
ps.setString(12, cut(book.getEdition(), 100));
ps.executeUpdate();
}
}
private void insertEbook(Connection connection, String table, long id, BookDocument book) throws SQLException {
String isbn13 = isbn13(book.getIsbn());
String sql = "INSERT INTO `" + table + "` (RECORD_ID, TITLE, AUTHOR, ISBN13, ISBN10, PUBLISHER, PUB_DATE, PUB_YEAR, DOC_ABSTRACT, KEYWORDS, FULLTEXT_LINK) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?)";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setLong(1, id);
ps.setString(2, cut(book.getTitle(), 1000));
ps.setString(3, cut(book.getAuthor(), 500));
ps.setString(4, cut(isbn13, 32));
ps.setString(5, isbn13.length() == 10 ? isbn13 : null);
ps.setString(6, cut(book.getPublisher(), 500));
ps.setString(7, cut(book.getPublishDate(), 32));
if (year(book.getPublishYear()) == null) {
ps.setObject(8, null);
} else {
ps.setInt(8, year(book.getPublishYear()));
}
ps.setString(9, cut(book.getSummary(), 500));
ps.setString(10, cut(book.getKeywords(), 255));
ps.setString(11, cut(book.getFulltextUrl(), 500));
ps.executeUpdate();
}
}
private boolean existsPaper(Connection connection, String table, BookDocument book) throws SQLException {
String isbn = isbn13(book.getIsbn());
if (!isbn.isEmpty()) {
try (PreparedStatement ps = connection.prepareStatement(
"SELECT 1 FROM `" + table + "` WHERE ISBN13 = ? OR ISBN = ? OR ISBN10 = ? LIMIT 1")) {
ps.setString(1, isbn);
ps.setString(2, book.getIsbn());
ps.setString(3, isbn);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return true;
}
}
}
}
return existsByTitle(connection, table, book);
}
private boolean existsEbook(Connection connection, String table, BookDocument book) throws SQLException {
String isbn = isbn13(book.getIsbn());
if (!isbn.isEmpty()) {
try (PreparedStatement ps = connection.prepareStatement(
"SELECT 1 FROM `" + table + "` WHERE ISBN13 = ? OR ISBN10 = ? OR EISBN = ? LIMIT 1")) {
ps.setString(1, isbn);
ps.setString(2, isbn);
ps.setString(3, isbn);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return true;
}
}
}
}
return existsByTitle(connection, table, book);
}
private boolean existsByTitle(Connection connection, String table, BookDocument book) throws SQLException {
try (PreparedStatement ps = connection.prepareStatement(
"SELECT 1 FROM `" + table + "` WHERE TITLE = ? AND IFNULL(AUTHOR,'') = ? LIMIT 1")) {
ps.setString(1, book.getTitle());
ps.setString(2, book.getAuthor() == null ? "" : book.getAuthor());
try (ResultSet rs = ps.executeQuery()) {
return rs.next();
}
}
}
private long maxId(Connection connection, String table) throws SQLException {
try (Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT IFNULL(MAX(RECORD_ID), 0) FROM `" + table + "`")) {
rs.next();
return rs.getLong(1);
}
}
private String table(String name, String fallback) {
String table = name == null || name.isBlank() ? fallback : name.trim();
if (!table.matches("[A-Za-z0-9_]+")) {
throw new BusinessException("图书表名不正确");
}
return table;
}
private String isbn13(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 Integer year(String value) {
if (value == null) {
return null;
}
StringBuilder digits = new StringBuilder();
for (int i = 0; i < value.length() && digits.length() < 4; i++) {
char c = value.charAt(i);
if (c >= '0' && c <= '9') {
digits.append(c);
}
}
if (digits.length() != 4) {
return null;
}
return Integer.parseInt(digits.toString());
}
private String first(String value, String fallback) {
return value == null || value.isBlank() ? fallback : value;
}
private String cut(String value, int max) {
if (value == null) {
return null;
}
String text = value.trim();
return text.length() <= max ? text : text.substring(0, max);
}
private String safe(String message, String password) {
if (message == null) {
return "写入失败";
}
if (password != null && !password.isBlank()) {
return message.replace(password, "******");
}
return message;
}
/** inserted 是新写入条数,skipped 是测试库里已经有、跳过的条数。 */
public record WriteResult(int inserted, int skipped) {
}
}
@@ -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,492 @@
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.reader.MysqlNodeWriter;
import com.banben.modules.synchub.store.BookStore;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
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 MysqlNodeWriter mysqlNodeWriter;
private final JdbcTemplate jdbcTemplate;
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());
if (node.getMysqlUrl() != null && !node.getMysqlUrl().isBlank()) {
List<BookDocument> page = readVersionResource(loadCursor(node.getCode()), properties.pageSize());
if (!page.isEmpty()) {
MysqlNodeWriter.WriteResult result = mysqlNodeWriter.write(node, page);
saveCursor(node.getCode(), page.get(page.size() - 1).getResourceId());
record.setBookCount(result.inserted());
record.setSkipCount(result.skipped());
}
} else {
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());
}
}
/**
* 配了 MySQL 的节点,从 version_resource 按批写成对方的书目表。
* 没配 MySQL 的节点,仍把缺的书送到对方的接收接口。
*/
private SyncHubRecord dispatchMissing(SyncHubProperties.Node node) {
if (node.getMysqlUrl() != null && !node.getMysqlUrl().isBlank()) {
return dispatchToMysql(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 SyncHubRecord dispatchToMysql(SyncHubProperties.Node node) {
long cursor = loadCursor(node.getCode());
int size = properties.pageSize();
int inserted = 0;
int skipped = 0;
boolean more = false;
try {
int pages = 0;
while (pages < 20 && inserted < size) {
List<BookDocument> page = readVersionResource(cursor, size);
if (page.isEmpty()) {
more = false;
break;
}
MysqlNodeWriter.WriteResult result = mysqlNodeWriter.write(node, page);
inserted += result.inserted();
skipped += result.skipped();
cursor = page.get(page.size() - 1).getResourceId();
saveCursor(node.getCode(), cursor);
pages++;
more = page.size() == size;
if (!more) {
break;
}
}
if (inserted == 0 && skipped == 0) {
return null;
}
SyncHubRecord record = open(DOWN, "NC_CENTER", node.getCode(), "VERSION_RESOURCE");
record.setBookCount(inserted);
record.setSkipCount(skipped);
if (more) {
record.setErrorMessage("version_resource 后面还有,请再调用一次回传");
}
succeed(record);
return record;
} catch (RuntimeException e) {
SyncHubRecord record = open(DOWN, "NC_CENTER", node.getCode(), "VERSION_RESOURCE");
record.setBookCount(inserted);
record.setSkipCount(skipped);
fail(record, e);
return record;
}
}
/** 从总库 version_resource 取 id 大于 afterId 的一页,不改这张表。 */
private List<BookDocument> readVersionResource(long afterId, int limit) {
return jdbcTemplate.query(
"SELECT id, process_no, title, other_title, author, isbn, publisher, publish_year, publish_date, "
+ "clc_code, edition, keywords, summary, media_type, fulltext_url "
+ "FROM version_resource WHERE deleted = 0 AND id > ? AND title IS NOT NULL AND title <> '' "
+ "ORDER BY id LIMIT ?",
(rs, rowNum) -> {
BookDocument book = new BookDocument();
book.setResourceId(rs.getLong("id"));
book.setProcessNo(rs.getString("process_no"));
book.setTitle(rs.getString("title"));
book.setOtherTitle(rs.getString("other_title"));
book.setAuthor(rs.getString("author"));
book.setIsbn(rs.getString("isbn"));
book.setPublisher(rs.getString("publisher"));
book.setPublishYear(rs.getString("publish_year"));
book.setPublishDate(rs.getString("publish_date"));
book.setClcCode(rs.getString("clc_code"));
book.setEdition(rs.getString("edition"));
book.setKeywords(rs.getString("keywords"));
book.setSummary(rs.getString("summary"));
book.setMediaType(rs.getString("media_type"));
book.setFulltextUrl(rs.getString("fulltext_url"));
book.setSourceDb("VERSION_RESOURCE");
book.setNodeCode("NC_CENTER");
return book;
},
afterId, limit);
}
private long loadCursor(String nodeCode) {
List<Long> ids = jdbcTemplate.query(
"SELECT last_resource_id FROM sync_hub_cursor WHERE node_code = ?",
(rs, rowNum) -> rs.getLong(1), nodeCode);
return ids.isEmpty() ? 0L : ids.get(0);
}
private void saveCursor(String nodeCode, long resourceId) {
jdbcTemplate.update(
"INSERT INTO sync_hub_cursor (node_code, last_resource_id, update_time) VALUES (?,?, CURRENT_TIMESTAMP) "
+ "ON CONFLICT (node_code) DO UPDATE SET last_resource_id = EXCLUDED.last_resource_id, update_time = CURRENT_TIMESTAMP",
nodeCode, resourceId);
}
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,35 @@ spring:
logging: logging:
level: level:
com.banben: debug com.banben: debug
# 节点与南昌总库的图书同步。
# 陆工大暂用 10.1.1.243 的 ljgc_db。下推时从 version_resource 按批读出,
# 纸质写入 book_attr,电子写入 e_book。不把总库两百万条一次写完。
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
mysql-url: jdbc:mysql://10.1.1.243:3306/ljgc_db?useSSL=false&allowPublicKeyRetrieval=true&connectTimeout=8000&characterEncoding=utf8
mysql-user: root
mysql-password: 123456
mysql-query: SELECT RECORD_ID AS process_no, TITLE AS title, AUTHOR AS author, ISBN13 AS isbn, PUBLISHER AS publisher, PUB_YEAR AS publish_year, CALL_NO AS clc_code FROM book_attr
paper-table: book_attr
ebook-table: e_book
- code: BHF
name: 边海防
kinds: MOCK
callback-url: http://127.0.0.1:8080
+2 -1
View File
@@ -23,7 +23,8 @@ mybatis-plus:
mapper-locations: classpath*:mapper/**/*.xml mapper-locations: classpath*:mapper/**/*.xml
configuration: configuration:
map-underscore-to-camel-case: true map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 使用 SLF4J,不要换成 StdOutImpl。StdOutImpl 会把结果集每一列打到 System.out,
# 大查询占住控制台锁后,登录等其它请求会一起卡住。
global-config: global-config:
banner: false banner: false
db-config: db-config:
@@ -0,0 +1,146 @@
-- =====================================================================
-- 版本资源元数据:补齐 32 个著录要素字段
-- 适用数据库:PostgreSQL / 瀚高(HighGo)
-- 说明:
-- 1. 本脚本【幂等】,可重复执行;仅当列不存在时才添加,不会对已建好
-- 完整表的库报错。
-- 2. 用于「实际运行库」是用更早版本表结构创建、尚缺这些列时的补列。
-- 3. schema.sql 已包含全部字段,新库直接执行 schema.sql 即可,无需本脚本。
-- =====================================================================
DO $$
BEGIN
-- ==================== 必备字段 ====================
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='process_no') THEN
ALTER TABLE version_resource ADD COLUMN process_no VARCHAR(128);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='title') THEN
ALTER TABLE version_resource ADD COLUMN title VARCHAR(512) NOT NULL DEFAULT '';
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='clc_code') THEN
ALTER TABLE version_resource ADD COLUMN clc_code VARCHAR(64);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='keywords') THEN
ALTER TABLE version_resource ADD COLUMN keywords VARCHAR(512);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='summary') THEN
ALTER TABLE version_resource ADD COLUMN summary TEXT;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='publish_year') THEN
ALTER TABLE version_resource ADD COLUMN publish_year VARCHAR(8);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='process_date') THEN
ALTER TABLE version_resource ADD COLUMN process_date VARCHAR(16);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='content_form') THEN
ALTER TABLE version_resource ADD COLUMN content_form VARCHAR(64);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='media_type') THEN
ALTER TABLE version_resource ADD COLUMN media_type VARCHAR(32);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='format') THEN
ALTER TABLE version_resource ADD COLUMN format VARCHAR(64);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='page_count') THEN
ALTER TABLE version_resource ADD COLUMN page_count VARCHAR(64);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='language') THEN
ALTER TABLE version_resource ADD COLUMN language VARCHAR(16);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='submit_org') THEN
ALTER TABLE version_resource ADD COLUMN submit_org VARCHAR(256);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='task_year') THEN
ALTER TABLE version_resource ADD COLUMN task_year VARCHAR(8);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='source_library') THEN
ALTER TABLE version_resource ADD COLUMN source_library VARCHAR(256);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='source_library_addr') THEN
ALTER TABLE version_resource ADD COLUMN source_library_addr VARCHAR(256);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='fulltext_url') THEN
ALTER TABLE version_resource ADD COLUMN fulltext_url VARCHAR(1024);
END IF;
-- ==================== 有则必备字段 ====================
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='other_title') THEN
ALTER TABLE version_resource ADD COLUMN other_title VARCHAR(512);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='author') THEN
ALTER TABLE version_resource ADD COLUMN author VARCHAR(512);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='responsibility') THEN
ALTER TABLE version_resource ADD COLUMN responsibility VARCHAR(256);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='note') THEN
ALTER TABLE version_resource ADD COLUMN note TEXT;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='publisher') THEN
ALTER TABLE version_resource ADD COLUMN publisher VARCHAR(256);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='publish_place') THEN
ALTER TABLE version_resource ADD COLUMN publish_place VARCHAR(128);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='publish_date') THEN
ALTER TABLE version_resource ADD COLUMN publish_date VARCHAR(32);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='relation') THEN
ALTER TABLE version_resource ADD COLUMN relation VARCHAR(512);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='time_range') THEN
ALTER TABLE version_resource ADD COLUMN time_range VARCHAR(256);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='space_range') THEN
ALTER TABLE version_resource ADD COLUMN space_range VARCHAR(256);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='edition') THEN
ALTER TABLE version_resource ADD COLUMN edition VARCHAR(128);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='isbn') THEN
ALTER TABLE version_resource ADD COLUMN isbn VARCHAR(64);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='unified_book_no') THEN
ALTER TABLE version_resource ADD COLUMN unified_book_no VARCHAR(64);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='cdoi') THEN
ALTER TABLE version_resource ADD COLUMN cdoi VARCHAR(256);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='publish_url') THEN
ALTER TABLE version_resource ADD COLUMN publish_url VARCHAR(1024);
END IF;
END $$;
-- 列注释(幂等,可重复执行)
COMMENT ON COLUMN version_resource.process_no IS '加工编号(必备)';
COMMENT ON COLUMN version_resource.title IS '正题名(必备)';
COMMENT ON COLUMN version_resource.clc_code IS '中图分类(必备)';
COMMENT ON COLUMN version_resource.keywords IS '主题词或关键词(必备,CCT标引,分隔符为分号)';
COMMENT ON COLUMN version_resource.summary IS '摘要(必备,不少于100字)';
COMMENT ON COLUMN version_resource.publish_year IS '出版年份(必备,yyyy)';
COMMENT ON COLUMN version_resource.process_date IS '加工日期(必备,yyyyMMdd)';
COMMENT ON COLUMN version_resource.content_form IS '内容形式(必备,GB/T 3469-2013)';
COMMENT ON COLUMN version_resource.media_type IS '媒体类型(必备:纸质/电子)';
COMMENT ON COLUMN version_resource.format IS '格式(必备,英文大写,如 TIF、PDF)';
COMMENT ON COLUMN version_resource.page_count IS '页码(必备)';
COMMENT ON COLUMN version_resource.language IS '语种(必备,3位语种代码)';
COMMENT ON COLUMN version_resource.submit_org IS '数据提交单位(必备)';
COMMENT ON COLUMN version_resource.task_year IS '所属任务年份(必备)';
COMMENT ON COLUMN version_resource.source_library IS '来源馆(必备)';
COMMENT ON COLUMN version_resource.source_library_addr IS '来源馆地址(必备,IP:端口或域名)';
COMMENT ON COLUMN version_resource.fulltext_url IS '全文地址(必备,根据CDOI生成)';
COMMENT ON COLUMN version_resource.other_title IS '其他题名(有则必备)';
COMMENT ON COLUMN version_resource.author IS '责任者名称(有则必备)';
COMMENT ON COLUMN version_resource.responsibility IS '责任方式(有则必备)';
COMMENT ON COLUMN version_resource.note IS '附注(有则必备)';
COMMENT ON COLUMN version_resource.publisher IS '出版者名称(有则必备)';
COMMENT ON COLUMN version_resource.publish_place IS '出版地(有则必备)';
COMMENT ON COLUMN version_resource.publish_date IS '出版日期(有则必备)';
COMMENT ON COLUMN version_resource.relation IS '关联(有则必备)';
COMMENT ON COLUMN version_resource.time_range IS '时间范围(有则必备)';
COMMENT ON COLUMN version_resource.space_range IS '空间范围(有则必备)';
COMMENT ON COLUMN version_resource.edition IS '版本/版次(有则必备)';
COMMENT ON COLUMN version_resource.isbn IS 'ISBN(有则必备)';
COMMENT ON COLUMN version_resource.unified_book_no IS '统一书号(有则必备)';
COMMENT ON COLUMN version_resource.cdoi IS 'CDOI(有则必备)';
COMMENT ON COLUMN version_resource.publish_url IS '发布地址(有则必备)';
@@ -0,0 +1,68 @@
-- 组织、角色,以及用户与二者的关联。可重复执行。
CREATE TABLE IF NOT EXISTS sys_org
(
id BIGSERIAL NOT NULL PRIMARY KEY,
parent_id BIGINT,
name VARCHAR(128) NOT NULL,
code VARCHAR(64),
sort_no INT DEFAULT 0,
status SMALLINT DEFAULT 1,
remark VARCHAR(256),
deleted SMALLINT DEFAULT 0,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_sys_org_parent ON sys_org (parent_id);
CREATE UNIQUE INDEX IF NOT EXISTS uk_sys_org_code
ON sys_org (code) WHERE deleted = 0 AND code IS NOT NULL AND code <> '';
COMMENT ON TABLE sys_org IS '组织,parent_id 为空表示顶级';
COMMENT ON COLUMN sys_org.parent_id IS '上级组织,空为顶级';
COMMENT ON COLUMN sys_org.name IS '组织名称';
COMMENT ON COLUMN sys_org.code IS '组织编码,未删除时唯一';
COMMENT ON COLUMN sys_org.sort_no IS '同级排序,小的在前';
COMMENT ON COLUMN sys_org.status IS '1启用 0停用';
CREATE TABLE IF NOT EXISTS sys_role
(
id BIGSERIAL NOT NULL PRIMARY KEY,
code VARCHAR(32) NOT NULL,
name VARCHAR(64) NOT NULL,
remark VARCHAR(256),
status SMALLINT DEFAULT 1,
builtin SMALLINT DEFAULT 0,
deleted SMALLINT DEFAULT 0,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX IF NOT EXISTS uk_sys_role_code
ON sys_role (code) WHERE deleted = 0;
COMMENT ON TABLE sys_role IS '角色。builtin=1 为内置角色,不可删除';
COMMENT ON COLUMN sys_role.code IS '角色编码,登录令牌沿用该编码';
COMMENT ON COLUMN sys_role.builtin IS '1内置 0自建';
INSERT INTO sys_role (code, name, remark, status, builtin)
SELECT 'ADMIN', '系统管理员', '系统内置,可管理组织、用户与角色', 1, 1
WHERE NOT EXISTS (SELECT 1 FROM sys_role WHERE code = 'ADMIN' AND deleted = 0);
INSERT INTO sys_role (code, name, remark, status, builtin)
SELECT 'USER', '普通用户', '系统内置普通用户', 1, 1
WHERE NOT EXISTS (SELECT 1 FROM sys_role WHERE code = 'USER' AND deleted = 0);
ALTER TABLE sys_user ADD COLUMN IF NOT EXISTS org_id BIGINT;
ALTER TABLE sys_user ADD COLUMN IF NOT EXISTS role_id BIGINT;
CREATE INDEX IF NOT EXISTS idx_sys_user_org ON sys_user (org_id);
CREATE INDEX IF NOT EXISTS idx_sys_user_role ON sys_user (role_id);
COMMENT ON COLUMN sys_user.org_id IS '所属组织,对应 sys_org.id';
COMMENT ON COLUMN sys_user.role_id IS '角色,对应 sys_role.id;role 列保存角色编码供登录使用';
UPDATE sys_user u
SET role_id = r.id
FROM sys_role r
WHERE u.role_id IS NULL
AND u.deleted = 0
AND r.deleted = 0
AND upper(u.role) = upper(r.code);
@@ -0,0 +1,32 @@
-- 角色可见的顶部导航。已有角色默认拥有全部栏目,之后可在角色管理里取消勾选。
-- menu_inited=1 后再次执行不会把已清空的栏目补回来。
CREATE TABLE IF NOT EXISTS sys_role_menu
(
id BIGSERIAL NOT NULL PRIMARY KEY,
role_id BIGINT NOT NULL,
menu_code VARCHAR(32) NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS uk_sys_role_menu ON sys_role_menu (role_id, menu_code);
COMMENT ON TABLE sys_role_menu IS '角色可访问的顶部导航编码';
COMMENT ON COLUMN sys_role_menu.menu_code IS '导航编码,如 dashboard、search';
ALTER TABLE sys_role ADD COLUMN IF NOT EXISTS menu_inited SMALLINT DEFAULT 0;
COMMENT ON COLUMN sys_role.menu_inited IS '1表示顶部导航已按角色保存过,重复执行不再补全';
INSERT INTO sys_role_menu (role_id, menu_code)
SELECT r.id, m.code
FROM sys_role r
CROSS JOIN (
VALUES ('dashboard'), ('search'), ('hotwords'), ('special'),
('deposit'), ('analysis'), ('resource'), ('collect'), ('governance')
) AS m(code)
WHERE r.deleted = 0
AND COALESCE(r.menu_inited, 0) = 0
AND NOT EXISTS (SELECT 1 FROM sys_role_menu x WHERE x.role_id = r.id);
UPDATE sys_role
SET menu_inited = 1
WHERE deleted = 0
AND COALESCE(menu_inited, 0) = 0;
@@ -0,0 +1,10 @@
-- 后台管理成为顶部导航的一项。已有的系统管理员默认拥有该栏目,其它角色需在角色管理里勾选。
INSERT INTO sys_role_menu (role_id, menu_code)
SELECT r.id, 'admin'
FROM sys_role r
WHERE r.deleted = 0
AND upper(r.code) = 'ADMIN'
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu x WHERE x.role_id = r.id AND x.menu_code = 'admin'
);
@@ -0,0 +1,15 @@
-- 系统管理员补齐全部顶部栏目。可重复执行,已有的不会重复插入。
INSERT INTO sys_role_menu (role_id, menu_code)
SELECT r.id, m.code
FROM sys_role r
CROSS JOIN (
VALUES ('dashboard'), ('search'), ('hotwords'), ('special'),
('deposit'), ('analysis'), ('resource'), ('collect'),
('governance'), ('admin')
) AS m(code)
WHERE r.deleted = 0
AND upper(r.code) = 'ADMIN'
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu x WHERE x.role_id = r.id AND x.menu_code = m.code
);
@@ -0,0 +1,37 @@
-- =====================================================================
-- 版本资源多来源表
-- 支持「一条文献可有多个来源,概览页按来源图标+名称展示并可分别下载」
-- 兼容 PostgreSQL / 瀚高(HighGo)
-- =====================================================================
CREATE TABLE IF NOT EXISTS resource_source
(
id BIGSERIAL NOT NULL PRIMARY KEY,
resource_id BIGINT NOT NULL,
source_repo VARCHAR(256),
source_library VARCHAR(256),
source_library_addr VARCHAR(256),
fulltext_url VARCHAR(1024),
process_no VARCHAR(128),
media_type VARCHAR(32),
sort_no INT DEFAULT 0,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
deleted SMALLINT DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_rs_resource_id ON resource_source (resource_id);
CREATE INDEX IF NOT EXISTS idx_rs_deleted ON resource_source (deleted);
COMMENT ON TABLE resource_source IS '版本资源多来源表(一条文献可来自多个资源库/来源馆)';
COMMENT ON COLUMN resource_source.resource_id IS '关联版本资源主记录ID';
COMMENT ON COLUMN resource_source.source_repo IS '来源资源库名';
COMMENT ON COLUMN resource_source.fulltext_url IS '全文下载地址';
-- 仅在无来源数据时为样例文献补全多来源(演示用,可重复执行)
INSERT INTO resource_source (resource_id, source_repo, source_library, source_library_addr, fulltext_url, process_no, media_type, sort_no)
SELECT v.id, '版本资源总库', v.source_library, v.source_library_addr, v.fulltext_url, v.process_no, v.media_type, 1
FROM version_resource v
WHERE v.id IN (1, 2)
AND v.deleted = 0
AND NOT EXISTS (SELECT 1 FROM resource_source s WHERE s.resource_id = v.id AND s.deleted = 0);
@@ -0,0 +1,36 @@
-- =====================================================================
-- 用户登录日志(会话维度)
-- 一次成功登录产生一条会话记录(online=1, logout_time=null);
-- 用户主动退出时回填 logout_time 并置 online=0。在线状态以 logout_time 为空为准。
-- 兼容 PostgreSQL / 瀚高(HighGo)
-- =====================================================================
CREATE TABLE IF NOT EXISTS login_log
(
id BIGSERIAL NOT NULL PRIMARY KEY,
user_id BIGINT,
username VARCHAR(128),
real_name VARCHAR(128),
org_name VARCHAR(256),
ip VARCHAR(64),
user_agent VARCHAR(512),
login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
logout_time TIMESTAMP,
online SMALLINT DEFAULT 1,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_ll_user_id ON login_log (user_id);
CREATE INDEX IF NOT EXISTS idx_ll_login_time ON login_log (login_time);
CREATE INDEX IF NOT EXISTS idx_ll_online ON login_log (online);
COMMENT ON TABLE login_log IS '用户登录日志(一次成功登录一条会话记录,登出写入 logout_time 并置 online=0)';
COMMENT ON COLUMN login_log.user_id IS '系统用户ID';
COMMENT ON COLUMN login_log.username IS '登录账号';
COMMENT ON COLUMN login_log.real_name IS '姓名';
COMMENT ON COLUMN login_log.org_name IS '所属单位';
COMMENT ON COLUMN login_log.ip IS '登录IP';
COMMENT ON COLUMN login_log.user_agent IS '浏览器/客户端标识';
COMMENT ON COLUMN login_log.login_time IS '登录时间';
COMMENT ON COLUMN login_log.logout_time IS '退出时间,未退出为 null';
COMMENT ON COLUMN login_log.online IS '是否在线:1在线 0离线';
@@ -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 '本次新写入的条数';
+68
View File
@@ -110,6 +110,31 @@ CREATE TABLE IF NOT EXISTS list_field_config
CREATE INDEX IF NOT EXISTS idx_lfc_scene ON list_field_config (scene, sort_no); CREATE INDEX IF NOT EXISTS idx_lfc_scene ON list_field_config (scene, sort_no);
-- 版本资源多来源表(一条文献可来自多个资源库/来源馆,概览页按来源展示并可分别下载)
CREATE TABLE IF NOT EXISTS resource_source
(
id BIGSERIAL NOT NULL PRIMARY KEY,
resource_id BIGINT NOT NULL, -- 关联 version_resource.id
source_repo VARCHAR(256), -- 来源资源库名
source_library VARCHAR(256), -- 来源馆
source_library_addr VARCHAR(256), -- 来源馆地址 IP:端口/域名
fulltext_url VARCHAR(1024), -- 全文地址(下载地址)
process_no VARCHAR(128), -- 加工编号(来源库内编号)
media_type VARCHAR(32), -- 媒体类型:纸质/电子
sort_no INT DEFAULT 0, -- 展示顺序(小在前)
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
deleted SMALLINT DEFAULT 0 -- 逻辑删除 0未删 1已删
);
CREATE INDEX IF NOT EXISTS idx_rs_resource_id ON resource_source (resource_id);
CREATE INDEX IF NOT EXISTS idx_rs_deleted ON resource_source (deleted);
COMMENT ON TABLE resource_source IS '版本资源多来源表(一条文献可来自多个资源库/来源馆)';
COMMENT ON COLUMN resource_source.resource_id IS '关联版本资源主记录ID';
COMMENT ON COLUMN resource_source.source_repo IS '来源资源库名';
COMMENT ON COLUMN resource_source.fulltext_url IS '全文下载地址';
-- 样例数据 -- 样例数据
INSERT INTO version_resource INSERT INTO version_resource
(id, process_no, title, clc_code, keywords, summary, publish_year, process_date, (id, process_no, title, clc_code, keywords, summary, publish_year, process_date,
@@ -132,3 +157,46 @@ ON CONFLICT (id) DO NOTHING;
-- 同步自增序列起点,避免与样例数据主键冲突 -- 同步自增序列起点,避免与样例数据主键冲突
SELECT setval('version_resource_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM version_resource), 0), 1), true); SELECT setval('version_resource_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM version_resource), 0), 1), true);
SELECT setval('special_resource_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM special_resource), 0), 1), true); SELECT setval('special_resource_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM special_resource), 0), 1), true);
-- 多来源演示数据:每条文献可归属多个资源库,概览页按来源图标+名称展示并可分别下载
INSERT INTO resource_source (resource_id, source_repo, source_library, source_library_addr, fulltext_url, process_no, media_type, sort_no)
VALUES
(1, '版本资源总库', '陆军步兵学院图书馆', '10.0.0.11:8080', 'http://cdio.example.org/fulltext/BB-2026-0001', 'BB-2026-0001', '纸质', 1),
(1, '军事理论特色库', '国防大学图书馆', '10.0.0.31:8080', 'http://cdio.example.org/fulltext/BB-2026-0001-dx', 'BB-2026-0001-DX', '电子', 2),
(2, '版本资源总库', '南京某院校图书馆', '10.0.0.21:8080', 'http://cdio.example.org/fulltext/BB-2026-0002', 'BB-2026-0002', '电子', 1),
(2, '电子图书镜像库', '西安某院校图书馆', '10.0.0.41:8080', 'http://cdio.example.org/fulltext/BB-2026-0002-mirror', 'BB-2026-0002-MIRROR', '电子', 2);
SELECT setval('resource_source_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM resource_source), 0), 1), true);
-- =====================================================================
-- 用户登录日志(会话维度):一次成功登录一条记录,登出写入 logout_time 并置 online=0
-- =====================================================================
CREATE TABLE IF NOT EXISTS login_log
(
id BIGSERIAL NOT NULL PRIMARY KEY,
user_id BIGINT,
username VARCHAR(128),
real_name VARCHAR(128),
org_name VARCHAR(256),
ip VARCHAR(64),
user_agent VARCHAR(512),
login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
logout_time TIMESTAMP,
online SMALLINT DEFAULT 1,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_ll_user_id ON login_log (user_id);
CREATE INDEX IF NOT EXISTS idx_ll_login_time ON login_log (login_time);
CREATE INDEX IF NOT EXISTS idx_ll_online ON login_log (online);
COMMENT ON TABLE login_log IS '用户登录日志(一次成功登录一条会话记录,登出写入 logout_time 并置 online=0)';
COMMENT ON COLUMN login_log.user_id IS '系统用户ID';
COMMENT ON COLUMN login_log.username IS '登录账号';
COMMENT ON COLUMN login_log.real_name IS '姓名';
COMMENT ON COLUMN login_log.org_name IS '所属单位';
COMMENT ON COLUMN login_log.ip IS '登录IP';
COMMENT ON COLUMN login_log.user_agent IS '浏览器/客户端标识';
COMMENT ON COLUMN login_log.login_time IS '登录时间';
COMMENT ON COLUMN login_log.logout_time IS '退出时间,未退出为 null';
COMMENT ON COLUMN login_log.online IS '是否在线:1在线 0离线';

Some files were not shown because too many files have changed in this diff Show More