feat: 操作日志模块(代码+SQL)

- 新增 @OperLog 注解,标记需记录的方法
- 新增 OperLogAspect AOP 切面,自动记录操作日志
- 新增 sys_oper_log 表结构
- 支持异步记录,不阻塞主流程
- application.yml 启用 @EnableAsync
This commit is contained in:
小蟑螂
2026-03-26 12:38:13 +08:00
parent eaa6de719e
commit d427fcfe7f
13 changed files with 543 additions and 302 deletions
+74 -164
View File
@@ -1,179 +1,89 @@
# AH-GF-Backend
# ecom-dmb-backend
AH-GF-Backend 是一个基于 Spring Boot 3.x + MyBatis Plus + Spring Security + JWT 的后端服务项目。
电商 DMB 后端服务
## 技术栈
- **Spring Boot 3.2.3** - 主框架
- **MyBatis Plus 3.5.5** - ORM框架
- **Spring Security** - 安全框架
- **JWT** - 身份认证
- **MySQL** - 数据库
- **Knife4j** - API文档
- **Lombok** - 代码简化
- **Maven** - 构建工具
- Java 17 + Spring Boot 3.2
- MyBatis-Plus + MySQL
- Redis(消息队列 + 缓存)
- JWT 认证(HS512)
- Knife4j API 文档
- Lombok + MapStruct
## 环境要求
- JDK 17+
- MySQL 8.0+
- Redis 6.0+
- Maven 3.9+
## 快速启动
### 1. 配置环境变量(生产环境必须)
```bash
export DB_URL="jdbc:mysql://<host>:3306/ecom_dmb_dev?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true"
export DB_USERNAME="ecom_dmb_dev"
export DB_PASSWORD="<your-db-password>"
export REDIS_HOST="<your-redis-host>"
export REDIS_PORT="6379"
export REDIS_PASSWORD="<your-redis-password>"
export JWT_SECRET="<your-64-byte-secret-key>"
```
### 2. 启动
```bash
cd ecom-dmb-backend
./mvnw spring-boot:run
```
或指定端口:
```bash
./mvnw spring-boot:run -Dspring-boot.run.arguments="--server.port=8080"
```
## 接口文档
启动后访问:http://localhost:8080/doc.html
## 项目结构
```
src/main/java/top/xyquan/ahgfbackend/
├── AhGfBackendApplication.java # 启动类
├── common/ # 公共模块
│ ├── exception/ # 异常处理
│ ├── model/ # 公共模型
│ └── response/ # 响应封装
├── config/ # 配置类
├── modules/ # 业务模块
│ ├── sys/ # 系统模块
│ │ ├── controller/ # 控制器
│ │ ├── mapper/ # 数据访问层
│ │ ├── model/ # 数据模型
│ │ │ ├── dto/ # 数据传输对象
│ │ │ ├── po/ # 持久化对象
│ │ │ └── vo/ # 视图对象
│ │ └── service/ # 业务逻辑层
│ └── org/ # 组织模块
└── utils/ # 工具类
ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/
├── common/ # 通用组件(异常、响应、注解、过滤器)
├── modules/
│ ├── ecom/ # 电商核心模块
│ │ ├── overview/ # 概览统计(含导出)
│ │ ├── order/ # 订单管理
│ │ ├── product/ # 商品管理
│ │ ├── shop/ # 店铺管理
│ │ ├── promotion/ # 推广费管理
│ │ ├── Brushorder/ # 刷单管理
│ │ └── importtask/ # 导入任务(Redis 队列)
│ └── sys/ # 系统模块(用户、菜单、权限)
└── utils/ # 工具类
```
## 功能特性
## 核心接口
### 用户认证模块
| 模块 | 路径 | 说明 |
|------|------|------|
| 公司概览 | POST /ec/company-overview/statistics | 全店铺汇总统计 |
| 公司概览导出 | POST /ec/company-overview/export | Excel 导出 |
| 店铺概览 | POST /ec/shop/overview-statistics | 单店铺统计 |
| 店铺导出 | POST /ec/shop/export-overview | Excel 导出 |
| 订单 | /ec/order/* | CRUD |
| 推广费 | /ec/promotion-fee/* | CRUD |
| 刷单 | /ec/brush-order/* | CRUD |
| 商品 | /ec/product/* | CRUD |
1. **用户注册**
- 支持通过登录账号或手机号码注册
- 密码加密存储
- 自动生成JWT令牌
## 数据库
2. **用户登录**
- 支持通过登录账号或手机号码登录
- 密码验证
- 返回JWT令牌和用户信息
连接信息通过环境变量配置,参考 application.yml 中的 `DB_*` 前缀。
3. **安全特性**
- 密码BCrypt加密
- JWT令牌认证
- 全局异常处理
- 参数验证
## 数据备份
## API接口
### 认证接口
#### 用户注册
- **URL**: `POST /api/auth/register`
- **请求体**:
```json
{
"loginCode": "用户名",
"phone": "手机号码",
"password": "密码"
}
```
- **说明**: loginCode和phone至少填写一个
#### 用户登录
- **URL**: `POST /api/auth/login`
- **请求体**:
```json
{
"account": "登录账号或手机号码",
"password": "密码"
}
```
## 数据库设计
### sys_user 表
用户表包含以下主要字段:
- `id`: 用户编号
- `login_code`: 登录账号
- `phone`: 手机号码
- `password`: 登录密码(加密存储)
- `real_name`: 用户名称
- `role`: 用户角色
- `status`: 用户状态
- `create_time`: 创建时间
- `update_time`: 更新时间
## 配置说明
### 数据库配置
在 `application.yml` 中配置数据库连接信息:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/your_database
username: your_username
password: your_password
```
### JWT配置
```yaml
jwt:
secret: your-secret-key
expiration: 86400
```
## 启动项目
1. **克隆项目**
```bash
git clone <repository-url>
cd ah-gf-backend
```
2. **配置数据库**
- 创建数据库
- 执行SQL脚本创建表
- 修改 `application.yml` 中的数据库配置
3. **启动项目**
```bash
mvn spring-boot:run
```
4. **访问API文档**
- 浏览器访问: `http://localhost:8080/doc.html`
## 开发规范
1. **代码规范**
- 遵循阿里巴巴Java开发手册
- 使用Lombok简化代码
- 统一异常处理
2. **架构设计**
- 模块化设计
- 分层架构(Controller -> Service -> Mapper)
- 单一职责原则
3. **安全规范**
- 密码加密存储
- JWT令牌认证
- 参数验证
## 测试
运行测试用例:
```bash
mvn test
```
## 部署
1. **打包**
```bash
mvn clean package
```
2. **运行**
```bash
java -jar target/ah-gf-backend-0.0.1-SNAPSHOT.jar
```
## 许可证
MIT License
参见项目根目录 `scripts/backup.sh`
@@ -3,8 +3,10 @@ package top.xyquan.ecomdmbbackend;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
@MapperScan({
"top.xyquan.ecomdmbbackend.modules.*.mapper",
"top.xyquan.ecomdmbbackend.modules.*.*.mapper"
@@ -0,0 +1,22 @@
package top.xyquan.ecomdmbbackend.modules.sys.operlog.annotation;
import java.lang.annotation.*;
/**
* 操作日志注解
* 标注在 Controller 方法上,自动记录操作日志
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperLog {
/** 模块名称,如"店铺管理"、"订单管理" */
String module() default "";
/** 操作类型 */
OperType type() default OperType.QUERY;
/** 操作描述,如"创建店铺"、"更新订单" */
String description() default "";
}
@@ -0,0 +1,24 @@
package top.xyquan.ecomdmbbackend.modules.sys.operlog.annotation;
/**
* 操作类型枚举
*/
public enum OperType {
QUERY("查询"),
CREATE("新增"),
UPDATE("更新"),
DELETE("删除"),
EXPORT("导出"),
IMPORT("导入"),
OTHER("其他");
private final String label;
OperType(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}
@@ -0,0 +1,178 @@
package top.xyquan.ecomdmbbackend.modules.sys.operlog.aspect;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.xyquan.ecomdmbbackend.modules.sys.operlog.annotation.OperLog;
import top.xyquan.ecomdmbbackend.modules.sys.operlog.model.po.SysOperLogPO;
import top.xyquan.ecomdmbbackend.modules.sys.operlog.service.SysOperLogService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
/**
* 操作日志 AOP 切面
* 自动拦截标注了 @OperLog 的 Controller 方法,记录操作日志
*/
@Aspect
@Component
public class OperLogAspect {
private static final Logger log = LoggerFactory.getLogger(OperLogAspect.class);
private static final int MAX_PARAMS_LEN = 2000;
private final SysOperLogService sysOperLogService;
private final CurrentUserContext currentUserContext;
public OperLogAspect(SysOperLogService sysOperLogService, CurrentUserContext currentUserContext) {
this.sysOperLogService = sysOperLogService;
this.currentUserContext = currentUserContext;
}
@Around("@annotation(top.xyquan.ecomdmbbackend.modules.sys.operlog.annotation.OperLog)")
public Object around(ProceedingJoinPoint point) throws Throwable {
long startTime = System.currentTimeMillis();
// 获取注解
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
OperLog operLog = method.getAnnotation(OperLog.class);
// 获取请求信息
HttpServletRequest request = getRequest();
String ip = request != null ? getIpAddress(request) : "unknown";
String url = request != null ? request.getRequestURI() : "";
String methodName = point.getTarget().getClass().getName() + "." + method.getName();
// 获取请求参数
String params = getParams(point);
// 执行目标方法
Object result = null;
String errorMsg = null;
String resultStatus = "success";
try {
result = point.proceed();
} catch (Throwable e) {
resultStatus = "fail";
errorMsg = e.getMessage();
throw e;
} finally {
long duration = System.currentTimeMillis() - startTime;
// 异步记录日志
try {
SysOperLogPO logPO = new SysOperLogPO();
logPO.setCompanyId(getCompanyIdSafely());
logPO.setUserId(getUserIdSafely());
logPO.setUsername(getUsernameSafely());
logPO.setModule(operLog.module());
logPO.setOperType(operLog.type().getLabel());
logPO.setDescription(operLog.description());
logPO.setMethod(methodName);
logPO.setUrl(url);
logPO.setParams(params.length() > MAX_PARAMS_LEN ? params.substring(0, MAX_PARAMS_LEN) : params);
logPO.setDuration(duration);
logPO.setIp(ip);
logPO.setResult(resultStatus);
logPO.setErrorMsg(errorMsg != null && errorMsg.length() > 500 ? errorMsg.substring(0, 500) : errorMsg);
logPO.setOperateTime(LocalDateTime.now());
sysOperLogService.saveLog(logPO);
} catch (Exception e) {
log.warn("保存操作日志失败: {}", e.getMessage());
}
}
return result;
}
private HttpServletRequest getRequest() {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attrs != null ? attrs.getRequest() : null;
}
private Long getCompanyIdSafely() {
try {
return currentUserContext.getCurrentCompanyId();
} catch (Exception e) {
return null;
}
}
private Long getUserIdSafely() {
try {
return currentUserContext.getCurrentUserId();
} catch (Exception e) {
return null;
}
}
private String getUsernameSafely() {
try {
return String.valueOf(currentUserContext.getCurrentUserId());
} catch (Exception e) {
return "unknown";
}
}
private String getParams(ProceedingJoinPoint point) {
try {
Object[] args = point.getArgs();
if (args == null || args.length == 0) return "";
StringBuilder sb = new StringBuilder();
for (Object arg : args) {
if (arg == null) continue;
// 跳过 HttpServletRequest/Response 等非业务参数
String className = arg.getClass().getName();
if (className.startsWith("jakarta.servlet") || className.startsWith("javax.servlet")) continue;
if (arg instanceof org.springframework.web.multipart.MultipartFile) continue;
try {
sb.append(",").append(arg.toString());
} catch (Exception e) {
sb.append(",[unserializable]");
}
}
return sb.length() > 0 ? sb.substring(1) : "";
} catch (Exception e) {
return "";
}
}
private String getIpAddress(HttpServletRequest request) {
try {
String[] headers = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR"
};
for (String header : headers) {
String ip = request.getHeader(header);
if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
return ip.split(",")[0].trim();
}
}
return request.getRemoteAddr();
} catch (Exception e) {
return "unknown";
}
}
}
@@ -0,0 +1,7 @@
package top.xyquan.ecomdmbbackend.modules.sys.operlog.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import top.xyquan.ecomdmbbackend.modules.sys.operlog.model.po.SysOperLogPO;
public interface SysOperLogMapper extends BaseMapper<SysOperLogPO> {
}
@@ -0,0 +1,59 @@
package top.xyquan.ecomdmbbackend.modules.sys.operlog.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 操作日志实体
*/
@Data
@TableName("sys_oper_log")
public class SysOperLogPO {
@TableId(type = IdType.AUTO)
private Long id;
/** 公司ID */
private Long companyId;
/** 用户ID */
private Long userId;
/** 用户名 */
private String username;
/** 模块名称 */
private String module;
/** 操作类型 */
private String operType;
/** 操作描述 */
private String description;
/** 请求方法 */
private String method;
/** 请求路径 */
private String url;
/** 请求参数(JSON 截断) */
private String params;
/** 执行时长(毫秒) */
private Long duration;
/** IP 地址 */
private String ip;
/** 操作结果:success / fail */
private String result;
/** 错误信息 */
private String errorMsg;
/** 操作时间 */
private LocalDateTime operateTime;
}
@@ -0,0 +1,17 @@
package top.xyquan.ecomdmbbackend.modules.sys.operlog.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import top.xyquan.ecomdmbbackend.modules.sys.operlog.model.po.SysOperLogPO;
public interface SysOperLogService {
/**
* 保存操作日志
*/
void saveLog(SysOperLogPO logPO);
/**
* 分页查询日志
*/
Page<SysOperLogPO> pageQuery(Long companyId, int page, int size, String module, String operType);
}
@@ -0,0 +1,41 @@
package top.xyquan.ecomdmbbackend.modules.sys.operlog.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.modules.sys.operlog.mapper.SysOperLogMapper;
import top.xyquan.ecomdmbbackend.modules.sys.operlog.model.po.SysOperLogPO;
import top.xyquan.ecomdmbbackend.modules.sys.operlog.service.SysOperLogService;
@Service
public class SysOperLogServiceImpl implements SysOperLogService {
private final SysOperLogMapper sysOperLogMapper;
public SysOperLogServiceImpl(SysOperLogMapper sysOperLogMapper) {
this.sysOperLogMapper = sysOperLogMapper;
}
@Override
@Async
public void saveLog(SysOperLogPO logPO) {
sysOperLogMapper.insert(logPO);
}
@Override
public Page<SysOperLogPO> pageQuery(Long companyId, int page, int size, String module, String operType) {
LambdaQueryWrapper<SysOperLogPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysOperLogPO::getCompanyId, companyId)
.orderByDesc(SysOperLogPO::getOperateTime);
if (module != null && !module.isBlank()) {
wrapper.like(SysOperLogPO::getModule, module);
}
if (operType != null && !operType.isBlank()) {
wrapper.eq(SysOperLogPO::getOperType, operType);
}
return sysOperLogMapper.selectPage(new Page<>(page, size), wrapper);
}
}
@@ -0,0 +1,22 @@
-- 操作日志表
CREATE TABLE IF NOT EXISTS `sys_oper_log` (
`id` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
`company_id` BIGINT DEFAULT NULL COMMENT '公司ID',
`user_id` BIGINT DEFAULT NULL COMMENT '用户ID',
`username` VARCHAR(100) DEFAULT NULL COMMENT '用户名',
`module` VARCHAR(100) DEFAULT NULL COMMENT '模块名称',
`oper_type` VARCHAR(20) DEFAULT NULL COMMENT '操作类型',
`description` VARCHAR(500) DEFAULT NULL COMMENT '操作描述',
`method` VARCHAR(500) DEFAULT NULL COMMENT '请求方法',
`url` VARCHAR(500) DEFAULT NULL COMMENT '请求路径',
`params` TEXT COMMENT '请求参数',
`duration` BIGINT DEFAULT NULL COMMENT '执行时长(ms)',
`ip` VARCHAR(50) DEFAULT NULL COMMENT 'IP地址',
`result` VARCHAR(20) DEFAULT NULL COMMENT '操作结果(success/fail)',
`error_msg` VARCHAR(1000) DEFAULT NULL COMMENT '错误信息',
`operate_time` DATETIME DEFAULT NULL COMMENT '操作时间',
INDEX `idx_company_id` (`company_id`),
INDEX `idx_user_id` (`user_id`),
INDEX `idx_operate_time` (`operate_time`),
INDEX `idx_module` (`module`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='操作日志表';