Duke Admin 后端开发手册
目录
项目概述
Duke Admin 后端是基于 Spring Boot 2.7.3 + MyBatis-Plus 构建的企业级后台管理系统后端服务。采用 DDD(领域驱动设计)分层架构,提供完整的用户管理、权限控制、系统监控等功能。
主要特性
- 🏗️ 基于 DDD 分层架构设计
- 🔐 集成 Spring Security + JWT 认证
- 📊 使用 MyBatis-Plus 进行数据访问
- 🗄️ 支持 MySQL 数据库
- 🔄 集成 Redis 缓存
- 📝 集成 Knife4j API 文档
- 🚀 基于 Spring Boot 2.7.3
- 🛡️ 完善的权限控制体系
技术栈
核心框架
- Spring Boot 2.7.3 - 快速构建 Spring 应用
- Spring Security - 安全框架
- MyBatis-Plus 3.5.3.1 - MyBatis 增强工具
- MySQL - 关系型数据库
- Redis - 缓存数据库
数据库连接池
- Druid 1.2.15 - 阿里巴巴数据库连接池
API 文档
- Knife4j 4.1.0 - 基于 OpenAPI 3 的接口文档
JSON 处理
- FastJSON 2.0.32 - 阿里巴巴 JSON 处理库
工具库
- Apache Commons Lang3 3.12.0 - 常用工具类
- Apache Commons IO 2.11.0 - IO 工具类
- Apache Commons Collections4 4.4 - 集合工具类
JWT 认证
- JJWT 0.11.5 - JWT 处理库
架构设计
DDD 分层架构
项目采用 DDD(领域驱动设计)分层架构,主要分为以下几层:
┌─────────────────────────────────────────────────────────────┐
│ 表现层 (Presentation) │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ Controller │ │ DTO │ │ Request/Response │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
└───────────────────────────┬─────────────────────────────────┘
│
┌───────────────────────────▼─────────────────────────────────┐
│ 应用层 (Application) │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ Service │ │ServiceImpl │ │ DomainService │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
└───────────────────────────┬─────────────────────────────────┘
│
┌───────────────────────────▼─────────────────────────────────┐
│ 领域层 (Domain) │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ Domain │ │Repository │ │ Business Rules │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
└───────────────────────────┬─────────────────────────────────┘
│
┌───────────────────────────▼─────────────────────────────────┐
│ 基础设施层 (Infrastructure) │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ Repository │ │ Cache │ │ Security/Auth │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
架构说明
1. 表现层 (Presentation Layer)
- Controller: 处理 HTTP 请求,参数校验,返回响应
- DTO: 定义接口的请求和响应数据结构
- Request/Response: 请求和响应对象
2. 应用层 (Application Layer)
- Service: 定义业务逻辑接口
- ServiceImpl: 实现具体的业务逻辑
- DomainService: 处理复杂的业务规则和领域逻辑
3. 领域层 (Domain Layer)
- Domain: 核心业务实体和业务规则
- Repository: 定义数据访问接口
- Business Rules: 业务规则和约束
4. 基础设施层 (Infrastructure Layer)
- Repository: 实现数据持久化
- Cache: 实现数据缓存
- Security/Auth: 实现认证和授权
项目结构
duke-boot/
├── duke-admin/ # 后台服务启动模块
│ ├── src/main/java/
│ │ └── com/duke/admin/
│ │ ├── common/ # 公共组件
│ │ ├── config/ # 配置类
│ │ ├── montior/ # 监控模块
│ │ ├── system/ # 系统管理
│ │ └── DukeApplication.java # 启动类
│ ├── src/main/resources/
│ │ ├── application.yml # 应用配置
│ │ └── mapper/ # MyBatis 映射文件
│ └── pom.xml
├── duke-common/ # 公共模块
│ ├── src/main/java/com/duke/common/
│ │ ├── cache/ # 缓存相关
│ │ ├── core/ # 核心组件
│ │ ├── database/ # 数据库相关
│ │ ├── exception/ # 异常处理
│ │ ├── handler/ # 处理器
│ │ ├── mapstruct/ # 对象映射
│ │ ├── message/ # 消息处理
│ │ ├── orm/ # ORM 相关
│ │ ├── utils/ # 工具类
│ │ ├── validator/ # 验证器
│ │ └── web/ # Web 相关
│ └── pom.xml
├── duke-framework/ # 框架核心模块
│ ├── src/main/java/com/duke/framework/
│ │ ├── code/ # 验证码
│ │ ├── security/ # 安全框架
│ │ └── token/ # Token 处理
│ └── pom.xml
├── duke-system/ # 系统管理模块
│ ├── src/main/java/com/duke/system/
│ │ ├── application/ # 应用层
│ │ ├── domain/ # 领域层
│ │ └── infrastructure/ # 基础设施层
│ └── pom.xml
├── duke-monitor/ # 监控模块
├── duke-boot.sql # 数据库脚本
├── pom.xml # 父 POM
└── README.md # 项目说明
模块详解
1. duke-admin 模块
后台服务启动模块,包含应用启动类和主要配置。
主要功能
- 应用启动入口
- 全局配置管理
- 安全配置
- 监控配置
核心类
DukeApplication.java: Spring Boot 启动类config/: 配置类目录common/: 公共组件
2. duke-common 模块
公共模块,提供各种通用功能和工具类。
主要包结构
- cache/: 缓存相关工具和配置
- core/: 核心组件和基础类
- database/: 数据库相关工具
- exception/: 异常处理机制
- handler/: 各种处理器
- mapstruct/: 对象映射工具
- message/: 消息处理
- orm/: ORM 相关工具
- utils/: 通用工具类
- validator/: 数据验证器
- web/: Web 相关工具
核心功能
- 统一响应格式
- 全局异常处理
- 数据验证
- 对象映射
- 缓存管理
- 工具类集合
3. duke-framework 模块
框架核心模块,提供安全认证和核心框架功能。
主要包结构
- code/: 验证码生成和验证
- security/: Spring Security 配置
- token/: JWT Token 处理
核心功能
- JWT 认证机制
- Spring Security 配置
- 验证码处理
- 权限控制
4. duke-system 模块
系统管理模块,采用 DDD 分层架构。
分层结构
application/: 应用层
- 服务接口和实现
- 应用服务
- 数据传输对象
domain/: 领域层
- 领域实体
- 领域服务
- 仓储接口
- 业务规则
infrastructure/: 基础设施层
- 仓储实现
- 数据访问对象
- 外部服务集成
主要功能
- 用户管理
- 角色管理
- 菜单管理
- 部门管理
- 岗位管理
- 字典管理
- 参数配置
5. duke-monitor 模块
系统监控模块,提供系统运行状态监控。
主要功能
- 在线用户监控
- 系统性能监控
- 操作日志
- 登录日志
开发环境搭建
环境要求
- JDK 1.8+
- Maven 3.6+
- MySQL 5.7+
- Redis 6.0+
安装步骤
- 克隆项目
git clone <repository-url>
cd duke-boot
- 数据库初始化
# 创建数据库
CREATE DATABASE duke CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
# 执行 SQL 脚本
mysql -u root -p duke < duke-boot.sql
- 配置数据库连接 编辑
duke-admin/src/main/resources/application.yml:
spring:
datasource:
url: jdbc:mysql://localhost:3306/duke?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: your_username
password: your_password
- 配置 Redis
spring:
redis:
host: localhost
port: 6379
password: your_redis_password
- 编译项目
mvn clean install
- 启动项目
mvn spring-boot:run
配置文件说明
application.yml 主要配置
server:
port: 8080
servlet:
context-path: /
spring:
application:
name: duke-admin
# 数据源配置
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/duke?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: root
password: password
# Redis 配置
redis:
host: localhost
port: 6379
password:
database: 0
# MyBatis Plus 配置
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
logic-delete-field: delFlag
logic-delete-value: 2
logic-not-delete-value: 0
# JWT 配置
jwt:
secret: duke-secret-key
expiration: 86400
# 日志配置
logging:
level:
com.duke: debug
开发规范
1. 代码规范
Java 代码规范
- 遵循阿里巴巴 Java 开发手册
- 使用 Lombok 简化代码
- 类名使用 PascalCase
- 方法名使用 camelCase
- 常量使用 UPPER_SNAKE_CASE
包命名规范
- 使用小写字母
- 使用点号分隔
- 按功能模块划分
类命名规范
- Controller 类以
Controller结尾 - Service 接口以
Service结尾 - Service 实现类以
ServiceImpl结尾 - Repository 接口以
Repository结尾 - 实体类使用领域名称
- DTO 类以
DTO结尾
2. 分层开发规范
Controller 层规范
@RestController
@RequestMapping("/system/user")
@Api(tags = "用户管理")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/list")
@ApiOperation("获取用户列表")
public AjaxResult list(UserQuery query) {
PageResult<UserVO> result = userService.getUserList(query);
return AjaxResult.success(result);
}
@PostMapping
@ApiOperation("新增用户")
public AjaxResult add(@Valid @RequestBody UserDTO userDTO) {
userService.addUser(userDTO);
return AjaxResult.success();
}
}
Service 层规范
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
@Transactional
public PageResult<UserVO> getUserList(UserQuery query) {
// 业务逻辑实现
Page<User> page = userRepository.selectPage(query);
return PageResult.of(page, UserVO.class);
}
@Override
@Transactional
public void addUser(UserDTO userDTO) {
// 参数验证
validateUser(userDTO);
// 业务逻辑
User user = UserConverter.INSTANCE.dtoToEntity(userDTO);
userRepository.insert(user);
}
}
Repository 层规范
@Repository
public interface UserRepository extends BaseRepository<User> {
@Select("SELECT * FROM sys_user WHERE username = #{username}")
User findByUsername(String username);
@Select("SELECT * FROM sys_user WHERE email = #{email}")
User findByEmail(String email);
}
3. 异常处理规范
自定义异常
public class BusinessException extends RuntimeException {
private String code;
public BusinessException(String message) {
super(message);
this.code = "500";
}
public BusinessException(String code, String message) {
super(message);
this.code = code;
}
}
全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public AjaxResult handleBusinessException(BusinessException e) {
return AjaxResult.error(e.getCode(), e.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public AjaxResult handleValidationException(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getFieldError().getDefaultMessage();
return AjaxResult.error("400", message);
}
}
4. 数据验证规范
实体类验证
public class UserDTO {
@NotBlank(message = "用户名不能为空")
@Size(min = 2, max = 20, message = "用户名长度必须在2-20之间")
private String username;
@NotBlank(message = "密码不能为空")
@Size(min = 6, max = 20, message = "密码长度必须在6-20之间")
private String password;
@Email(message = "邮箱格式不正确")
private String email;
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
private String phone;
}
API 文档
接口规范
统一响应格式
{
"code": 200,
"message": "操作成功",
"data": {
// 响应数据
},
"timestamp": 1640995200000
}
分页响应格式
{
"code": 200,
"message": "操作成功",
"data": {
"total": 100,
"list": [
// 数据列表
],
"pageNum": 1,
"pageSize": 10
}
}
主要接口
用户管理接口
GET /system/user/list- 获取用户列表GET /system/user/{id}- 获取用户详情POST /system/user- 新增用户PUT /system/user- 更新用户DELETE /system/user/{ids}- 删除用户
角色管理接口
GET /system/role/list- 获取角色列表POST /system/role- 新增角色PUT /system/role- 更新角色DELETE /system/role/{ids}- 删除角色
菜单管理接口
GET /system/menu/list- 获取菜单列表GET /system/menu/tree- 获取菜单树POST /system/menu- 新增菜单PUT /system/menu- 更新菜单DELETE /system/menu/{id}- 删除菜单
API 文档访问
启动项目后,访问以下地址查看 API 文档:
- Knife4j 文档:http://localhost:8080/doc.html
- Swagger 文档:http://localhost:8080/swagger-ui.html
部署指南
1. 开发环境部署
# 编译项目
mvn clean package -DskipTests
# 运行项目
java -jar duke-admin/target/duke-admin.jar
2. 生产环境部署
Docker 部署
FROM openjdk:8-jre-alpine
COPY duke-admin/target/duke-admin.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]
传统部署
# 1. 编译项目
mvn clean package -DskipTests
# 2. 上传 jar 包到服务器
# 3. 创建启动脚本
#!/bin/bash
java -Xms512m -Xmx1024m -jar duke-admin.jar --spring.profiles.active=prod
# 4. 启动服务
nohup ./start.sh > app.log 2>&1 &
3. 环境配置
生产环境配置 (application-prod.yml)
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://prod-db:3306/duke?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
redis:
host: prod-redis
port: 6379
password: ${REDIS_PASSWORD}
logging:
level:
com.duke: info
file:
name: logs/duke-admin.log
4. 监控和运维
健康检查
- 健康检查接口:
GET /actuator/health - 应用信息:
GET /actuator/info
日志管理
- 应用日志:
logs/duke-admin.log - 错误日志:
logs/error.log
性能监控
- JVM 监控
- 数据库连接池监控
- Redis 连接监控
常见问题
1. 启动问题
Q: 应用启动失败 A: 检查数据库连接配置,确保 MySQL 和 Redis 服务正常运行。
Q: 端口被占用 A: 修改 application.yml 中的 server.port 配置。
2. 数据库问题
Q: 数据库连接失败 A: 检查数据库连接配置,确保数据库服务正常运行,用户权限正确。
Q: 表不存在 A: 执行 duke-boot.sql 脚本初始化数据库。
3. 权限问题
Q: 接口返回 403 错误 A: 检查用户权限配置,确保用户具有访问该接口的权限。
Q: JWT Token 无效 A: 检查 JWT 配置,确保前后端使用相同的密钥。
4. 性能问题
Q: 接口响应慢 A: 检查数据库查询性能,添加适当的索引,使用缓存。
Q: 内存占用高 A: 调整 JVM 参数,优化数据库连接池配置。
更新日志
v1.0.0
- 初始版本发布
- 基于 DDD 分层架构
- 集成 Spring Security + JWT
- 完整的用户权限管理
- 系统监控功能
- API 文档集成
