# rui-common-core 使用手册 > **文件名**:`rui-common-core使用手册.md` > **存放位置**:`docs/rui-common-core使用手册.md` > > **文档定位**:本文档是 `rui-common-core` 模块的**唯一权威参考**,记录所有工具类、注解、事件、DTO 的功能与用法。 > > **使用规则**: > 1. **开发前先查本文档**:使用任何通用工具/注解/常量前,优先查阅本文档确认是否存在可用实现 > 2. **新增即更新**:向 `rui-common-core` 模块新增/修改任何类、方法时,**必须同步更新本文档** > 3. **禁止重复造轮子**:本文档中已有的工具,禁止在业务模块中重新实现 --- ## 1. 模块概述 `rui-common-core` 是睿核通用平台框架的**核心基础模块**,为所有上层模块提供通用的工具类、常量、异常、上下文持有器、注解、事件、DTO 等基础能力。 > **定位**:无业务依赖,无 Spring 依赖(除 SpringUtil、LoginEvent 外),可被任意模块引用。 --- ## 2. 功能清单 ### 2.1 上下文持有器(holder) | 类名 | 功能 | 说明 | |------|------|------| | `TenantContextHolder` | 租户上下文 | 线程隔离的租户 ID 存储,支持父子线程传递 | | `LocaleContextHolder` | 本地化上下文 | 线程隔离的语言环境存储 | ### 2.2 工具类(util) | 类名 | 功能 | 依赖 | |------|------|------| | `ServletUtil` | Servlet 请求工具 | 获取 IP、参数、Header、请求体等 | | `SpringUtil` | Spring 上下文工具 | 获取 Bean、配置、Environment、判断环境 | | `JsonUtil` | JSON 工具 | 基于 Fastjson2,对象与 JSON 互转 | | `DateUtil` | 日期时间工具 | 基于 JDK 8 java.time,格式化、解析、计算 | | `IdWorker` | 雪花算法 ID 生成器 | 分布式唯一 ID,支持趋势递增 | | `BeanUtil` | Bean 拷贝工具 | 基于 Spring BeanUtils,支持列表拷贝 | | `EncryptUtil` | 加密工具 | MD5、SHA-256、AES、Base64 | | `ValidateUtil` | 校验工具 | 手机号、邮箱、身份证、URL、密码等校验 | | `StringUtil` | 字符串扩展工具 | 驼峰/下划线转换、脱敏、截取等 | | `ThreadUtil` | 线程工具 | 线程池创建、优雅关闭、命名线程工厂 | | `FileUtil` | 文件工具 | 读写、复制、移动、目录操作、大小格式化 | | `UserNoGenerator` | 用户编号生成器 | 生成 U0001 格式编号,自动跳过保留靓号 | ### 2.3 异常(exception) | 类名 | 功能 | |------|------| | `BizException` | 业务异常,统一业务错误抛出 | ### 2.4 常量(constants) | 类名 | 功能 | |------|------| | `SecurityConstant` | 安全相关常量(Token 前缀、Header 名称等) | ### 2.5 模型(model) | 类名 | 功能 | |------|------| | `PageResult` | 统一分页结果封装 | ### 2.6 结果封装(result) | 类名 | 功能 | |------|------| | `Result` | 统一 API 返回结果(code、msg、data) | | `ResultCode` | 统一错误码枚举 | ### 2.7 注解(annotation) | 类名 | 功能 | 目标位置 | |------|------|---------| | `DataScope` | 数据权限注解,自动拼接数据范围 SQL | Service 方法 | ### 2.8 事件(event) | 类名 | 功能 | 说明 | |------|------|------| | `LoginEvent` | 登录事件 | 登录成功/失败时发布,供监听器记录日志 | ### 2.9 DTO(dto) | 类名 | 功能 | 说明 | |------|------|------| | `OperLogDTO` | 操作日志 DTO | 跨服务传输操作日志数据 | ### 2.10 拦截器上下文(interceptor) | 类名 | 功能 | 说明 | |------|------|------| | `DataScopeContext` | 数据权限上下文 | ThreadLocal 存储数据范围信息,需手动清理 | --- ## 3. 工具类详细说明 ### 3.1 IdWorker(雪花算法) ```java // 生成唯一 ID long id = IdWorker.nextIdLong(); String idStr = IdWorker.nextIdStr(); // 从 ID 中提取信息 long timestamp = IdWorker.extractTimestamp(id); long workerId = IdWorker.extractWorkerId(id); ``` ### 3.2 DateUtil(日期时间) ```java // 获取当前时间 String now = DateUtil.now(); // 2024-01-01 12:00:00 String today = DateUtil.today(); // 2024-01-01 // 格式化与解析 String str = DateUtil.format(LocalDateTime.now()); LocalDateTime dt = DateUtil.parse("2024-01-01 12:00:00"); // 计算 LocalDateTime tomorrow = DateUtil.plusDays(dt, 1); long days = DateUtil.betweenDays(start, end); ``` ### 3.3 JsonUtil(JSON 处理) ```java // 对象转 JSON String json = JsonUtil.toJsonString(user); // JSON 转对象 User user = JsonUtil.parseObject(json, User.class); List list = JsonUtil.parseList(json, User.class); Map map = JsonUtil.parseMap(json); ``` ### 3.4 EncryptUtil(加密) ```java // MD5 String md5 = EncryptUtil.md5("password"); // SHA-256 String sha256 = EncryptUtil.sha256("password"); // AES 对称加密 String encrypt = EncryptUtil.aesEncrypt("content", "1234567890123456"); String decrypt = EncryptUtil.aesDecrypt(encrypt, "1234567890123456"); // Base64 String base64 = EncryptUtil.base64Encode("content"); ``` ### 3.5 ValidateUtil(校验) ```java // 常用校验 boolean isMobile = ValidateUtil.isMobile("13800138000"); boolean isEmail = ValidateUtil.isEmail("test@example.com"); boolean isIdCard = ValidateUtil.isIdCard("110101199001011234"); boolean isUrl = ValidateUtil.isUrl("https://example.com"); boolean isIpv4 = ValidateUtil.isIpv4("192.168.1.1"); // 密码强度 boolean validPwd = ValidateUtil.isValidPassword("Abc123456"); ``` ### 3.6 SpringUtil(Spring 上下文) ```java // 获取 Bean UserService service = SpringUtil.getBean(UserService.class); // 获取配置 String value = SpringUtil.getProperty("server.port"); // 判断环境 boolean isDev = SpringUtil.isDev(); boolean isProd = SpringUtil.isProd(); ``` ### 3.7 BeanUtil(Bean 拷贝) ```java // 对象拷贝 UserDTO dto = BeanUtil.copyProperties(user, UserDTO.class); // 列表拷贝 List dtoList = BeanUtil.copyList(userList, UserDTO.class); // 忽略 null 值拷贝(用于更新) BeanUtil.copyNonNullProperties(source, target); ``` ### 3.8 StringUtil(字符串扩展) ```java // 命名转换 String camel = StringUtil.underlineToCamel("user_name"); // userName String underline = StringUtil.camelToUnderline("userName"); // user_name // 脱敏 String mobile = StringUtil.desensitizeMobile("13800138000"); // 138****8000 String email = StringUtil.desensitizeEmail("test@example.com"); // t***@example.com // 其他 String truncated = StringUtil.truncate("很长的字符串", 5); // 很长的字... ``` ### 3.9 ThreadUtil(线程池) ```java // 创建线程池 ExecutorService pool = ThreadUtil.newFixedPool(4, "my-pool"); ScheduledExecutorService scheduled = ThreadUtil.newScheduledPool(2, "schedule"); // 推荐:自定义线程池 ThreadPoolExecutor executor = ThreadUtil.newThreadPool( 4, 8, 60, 100, "business" ); // 优雅关闭 ThreadUtil.shutdown(pool, 30); ``` ### 3.10 FileUtil(文件操作) ```java // 读写 String content = FileUtil.readString("/path/file.txt"); FileUtil.writeString("/path/file.txt", "content"); FileUtil.appendString("/path/file.txt", "append"); // 目录 FileUtil.createDir("/path/dir"); FileUtil.delete("/path/file.txt"); // 信息 boolean exists = FileUtil.exists("/path/file.txt"); long size = FileUtil.size("/path/file.txt"); String sizeStr = FileUtil.formatSize(1024 * 1024); // 1.00 MB ``` ### 3.11 UserNoGenerator(用户编号生成器) ```java // 生成格式化的用户编号(U0001、U0002...) String userNo = UserNoGenerator.format(1); // U0001 // 判断是否为保留靓号(豹子号、连号、含666/888/999) boolean reserved = UserNoGenerator.isReserved("U1111"); // true // 生成下一个可用编号(自动跳过保留号) String next = UserNoGenerator.generate(1); // U0001(如果 U0001 是靓号则自动跳过) ``` --- ## 4. 注解使用说明 ### 4.1 @DataScope(数据权限) 标记在 Service 方法上,由 MyBatis Plus 拦截器自动拼接数据范围 SQL。 ```java @DataScope(deptField = "dept_id", userField = "create_by") public List list() { return baseMapper.selectList(); } ``` **参数说明**: - `deptField`:部门字段名,默认 `"dept_id"` - `userField`:用户字段名,默认 `"create_by"` **数据范围类型**(由 `DataScopeContext` 设置): - `1`:全部数据 - `2`:本部门数据 - `3`:本部门及子部门数据 - `4`:仅本人数据 - `5`:自定义数据 --- ## 5. 事件使用说明 ### 5.1 LoginEvent(登录事件) 登录成功或失败时发布,供其他模块监听记录日志。 ```java // 发布事件 applicationEventPublisher.publishEvent( new LoginEvent(this, userId, username, 1, clientId, ip, location, browser, os, 1, "登录成功") ); // 监听事件 @Component public class LoginEventListener { @EventListener public void onLogin(LoginEvent event) { // 记录登录日志 } } ``` --- ## 6. DTO 使用说明 ### 6.1 OperLogDTO(操作日志 DTO) 用于跨服务传输操作日志数据。 ```java OperLogDTO log = new OperLogDTO(); log.setTitle("用户管理"); log.setOperType(2); // 修改 log.setOperTypeName("修改用户"); log.setRequestUrl("/user/admin/user"); log.setRequestMethod("PUT"); log.setUserId(userId); log.setStatus(1); // 成功 ``` --- ## 7. 上下文使用说明 ### 7.1 TenantContextHolder(租户上下文) ```java // 设置租户ID TenantContextHolder.setTenantId(100L); // 获取租户ID Long tenantId = TenantContextHolder.getTenantId(); // 清理(必须在线程结束时调用) TenantContextHolder.clear(); ``` ### 7.2 DataScopeContext(数据权限上下文) ```java // 设置数据范围 DataScopeContext.setDataScope(2); // 本部门 DataScopeContext.setUserId(userId); DataScopeContext.setDeptId(deptId); // 获取数据范围 Integer scope = DataScopeContext.getDataScope(); // 清理(必须在线程结束时调用,防止内存泄漏) DataScopeContext.clear(); ``` --- ## 8. 使用方式 ### 8.1 Maven 依赖 ```xml com.rui rui-common-core ${revision} ``` ### 8.2 在业务模块中使用 ```java import com.rui.common.core.util.*; @Service public class UserService { public void createUser(User user) { // 生成唯一 ID user.setId(IdWorker.nextIdLong()); // 生成用户编号 user.setUserNo(UserNoGenerator.generate(seq)); // 日期处理 user.setCreatedAt(DateUtil.nowDateTime()); // 密码加密 user.setPassword(EncryptUtil.md5(user.getPassword())); // 保存... } } ``` --- ## 9. 规范说明 ### 9.1 工具类设计原则 1. **无状态**:所有工具类均为无状态静态方法,线程安全 2. **不可实例化**:通过 private 构造器防止实例化 3. **异常处理**:内部捕获并转换为 RuntimeException,避免污染业务代码 4. **空安全**:所有方法对 null 参数有处理,避免 NPE ### 9.2 新增规范 如需向本模块新增类,请遵循: 1. **包名规范**: - 工具类:`com.rui.common.core.util` - 注解:`com.rui.common.core.annotation` - 事件:`com.rui.common.core.event` - DTO:`com.rui.common.core.dto` - 上下文:`com.rui.common.core.holder` / `interceptor` - 常量:`com.rui.common.core.constants` - 异常:`com.rui.common.core.exception` 2. **命名规范**: - 工具类:以 `Util` 结尾,如 `XxxUtil` - 注解:以功能命名,如 `@DataScope` - 事件:以 `Event` 结尾,如 `XxxEvent` - DTO:以 `DTO` 结尾,如 `XxxDTO` 3. **方法规范**:均为 public static(工具类) 4. **文档规范**:类注释和方法注释使用中文 5. **测试规范**:建议补充单元测试 6. **文档同步**:**新增/修改后必须同步更新本文档** --- ## 10. 文档维护说明 ### 10.1 何时更新本文档 | 场景 | 操作 | |------|------| | 新增工具类/注解/事件/DTO | 在功能清单中添加条目,在详细说明中添加使用示例 | | 修改现有类的方法签名 | 同步更新对应详细说明中的代码示例 | | 删除类或方法 | 从文档中移除对应条目,并在版本历史中注明 | | 发现文档与代码不一致 | 以代码为准,修正文档 | ### 10.2 版本历史 | 日期 | 版本 | 变更内容 | |------|------|---------| | 2024-01 | 1.0 | 初始版本,包含基础工具类 | | 2024-06 | 1.1 | 新增 IdWorker、BeanUtil、ThreadUtil | | 2026-05 | 1.2 | 补充完整工具类集合,新增文档 | | 2026-06 | 1.3 | 新增 UserNoGenerator、DataScope 注解、LoginEvent、OperLogDTO、DataScopeContext;补充文档使用说明 |