423 lines
11 KiB
Markdown
423 lines
11 KiB
Markdown
# 微服务开发规范文档
|
||
|
||
## 项目概述
|
||
本文档记录了当前微服务项目的技术栈、依赖版本、代码风格和项目结构,供新微服务开发时参考。
|
||
|
||
## 技术栈版本
|
||
|
||
### 核心框架版本
|
||
- **Java版本**: 21
|
||
- **Spring Boot**: 3.1.5
|
||
- **Spring Cloud**: 2022.0.4
|
||
- **Spring Cloud Alibaba**: 2022.0.0.0
|
||
- **Maven**: 3.x
|
||
|
||
### 主要依赖版本
|
||
```xml
|
||
<!-- 核心依赖 -->
|
||
<parent>
|
||
<groupId>org.springframework.boot</groupId>
|
||
<artifactId>spring-boot-starter-parent</artifactId>
|
||
<version>3.1.5</version>
|
||
</parent>
|
||
|
||
<!-- 数据库相关 -->
|
||
<mybatis-plus.version>3.5.3.1</mybatis-plus.version>
|
||
<mysql-connector-j.version>8.2.0</mysql-connector-j.version>
|
||
|
||
<!-- 缓存相关 -->
|
||
<spring-session.version>3.1.1</spring-session.version>
|
||
|
||
<!-- 阿里云相关 -->
|
||
<aliyun-sdk-version>2.0.23</aliyun-sdk-version>
|
||
|
||
<!-- 文档相关 -->
|
||
<springdoc-openapi.version>2.3.0</springdoc-openapi.version>
|
||
|
||
<!-- 微信支付 -->
|
||
<wechatpay-java.version>0.2.16</wechatpay-java.version>
|
||
|
||
<!-- 阿里云凭证 -->
|
||
<credentials-java.version>0.3.10</credentials-java.version>
|
||
```
|
||
|
||
## 项目结构规范
|
||
|
||
### 标准目录结构
|
||
```
|
||
src/main/java/com/example/{service-name}/
|
||
├── annotation/ # 自定义注解
|
||
├── aspect/ # AOP切面
|
||
├── {ServiceName}Application.java # 启动类
|
||
├── common/ # 公共类
|
||
│ ├── exception/ # 异常处理
|
||
│ ├── Result.java # 统一响应结果
|
||
│ └── ResultCode.java # 响应码枚举
|
||
├── config/ # 配置类
|
||
├── constant/ # 常量类
|
||
├── controller/ # 控制器
|
||
├── dto/ # 数据传输对象
|
||
│ ├── request/ # 请求DTO
|
||
│ ├── response/ # 响应DTO
|
||
│ └── common/ # 公共DTO
|
||
├── entity/ # 实体类
|
||
├── feign/ # Feign客户端
|
||
├── mapper/ # MyBatis映射器
|
||
├── scheduled/ # 定时任务
|
||
├── service/ # 业务服务
|
||
├── typehandler/ # 类型处理器
|
||
└── util/ # 工具类
|
||
```
|
||
|
||
### 资源文件结构
|
||
```
|
||
src/main/resources/
|
||
├── application.yml # 主配置文件
|
||
├── application-pro.yml # 生产环境配置
|
||
└── mapper/ # MyBatis XML映射文件
|
||
└── *.xml
|
||
```
|
||
|
||
## 代码风格规范
|
||
|
||
### 1. 启动类规范
|
||
```java
|
||
@SpringBootApplication
|
||
@EnableDiscoveryClient
|
||
@EnableFeignClients("com.example.{service-name}.feign")
|
||
@EnableScheduling
|
||
@MapperScan("com.example.{service-name}.mapper")
|
||
public class {ServiceName}Application {
|
||
public static void main(String[] args) {
|
||
SpringApplication.run({ServiceName}Application.class, args);
|
||
}
|
||
}
|
||
```
|
||
|
||
### 2. 统一响应结果类
|
||
```java
|
||
@Data
|
||
public class Result<T> {
|
||
private Integer code;
|
||
private String message;
|
||
private T data;
|
||
|
||
public Result() {}
|
||
|
||
public Result(Integer code, String message, T data) {
|
||
this.code = code;
|
||
this.message = message;
|
||
this.data = data;
|
||
}
|
||
|
||
public static <T> Result<T> success() {
|
||
return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null);
|
||
}
|
||
|
||
public static <T> Result<T> success(T data) {
|
||
return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
|
||
}
|
||
|
||
public static <T> Result<T> error(String message) {
|
||
return new Result<>(ResultCode.ERROR.getCode(), message, null);
|
||
}
|
||
|
||
public static <T> Result<T> error(ResultCode resultCode) {
|
||
return new Result<>(resultCode.getCode(), resultCode.getMessage(), null);
|
||
}
|
||
}
|
||
```
|
||
|
||
### 3. 实体类规范
|
||
```java
|
||
@Data
|
||
@TableName("table_name")
|
||
public class EntityName {
|
||
@TableId(type = IdType.AUTO)
|
||
private Long id;
|
||
|
||
private String fieldName;
|
||
|
||
@TableField("is_deleted")
|
||
private Integer isDeleted;
|
||
|
||
@TableField(exist = false)
|
||
private Boolean customField; // 非数据库字段
|
||
|
||
private LocalDateTime createdAt;
|
||
private LocalDateTime updatedAt;
|
||
}
|
||
```
|
||
|
||
### 4. 控制器规范
|
||
```java
|
||
@Tag(name = "模块名称")
|
||
@Slf4j
|
||
@RestController
|
||
@RequestMapping("/api/v1/module")
|
||
@RequiredArgsConstructor
|
||
public class ModuleController {
|
||
|
||
private final ModuleService moduleService;
|
||
|
||
@Operation(summary = "接口描述")
|
||
@GetMapping("/endpoint")
|
||
public Result<ResponseType> methodName() {
|
||
// 业务逻辑
|
||
return Result.success(data);
|
||
}
|
||
}
|
||
```
|
||
|
||
### 5. 服务接口规范
|
||
```java
|
||
@Service
|
||
public interface ModuleService extends IService<EntityName> {
|
||
// 自定义业务方法
|
||
}
|
||
```
|
||
|
||
### 6. DTO规范
|
||
```java
|
||
@Data
|
||
public class ModuleRequest {
|
||
/**
|
||
* 字段描述
|
||
*/
|
||
private String fieldName;
|
||
}
|
||
```
|
||
|
||
## 配置文件规范
|
||
|
||
### 1. 主配置文件 (application.yml)
|
||
```yaml
|
||
server:
|
||
port: 8080
|
||
|
||
spring:
|
||
application:
|
||
name: {service-name}
|
||
profiles:
|
||
active: test
|
||
data:
|
||
redis:
|
||
username: default
|
||
host: ${REDIS_HOST:localhost}
|
||
port: ${REDIS_PORT:6379}
|
||
password: ${REDIS_PASSWORD:}
|
||
database: 0
|
||
timeout: 10000ms
|
||
lettuce:
|
||
pool:
|
||
max-active: 8
|
||
max-idle: 8
|
||
min-idle: 0
|
||
max-wait: -1ms
|
||
session:
|
||
store-type: redis
|
||
timeout: 30m
|
||
mvc:
|
||
pathmatch:
|
||
matching-strategy: ant_path_matcher
|
||
cloud:
|
||
nacos:
|
||
discovery:
|
||
server-addr: ${NACOS_SERVER:localhost:8848}
|
||
namespace: ${spring.profiles.active}
|
||
username: ${NACOS_USERNAME:nacos}
|
||
password: ${NACOS_PASSWORD:nacos}
|
||
loadbalancer:
|
||
ribbon:
|
||
enabled: false
|
||
|
||
# MongoDB配置 (新微服务使用)
|
||
spring:
|
||
data:
|
||
mongodb:
|
||
uri: ${MONGODB_URI:mongodb://localhost:27017/database_name}
|
||
database: ${MONGODB_DATABASE:database_name}
|
||
|
||
# 日志配置
|
||
logging:
|
||
level:
|
||
org.springframework.security: DEBUG
|
||
com.example.{service-name}: DEBUG
|
||
|
||
# Feign配置
|
||
feign:
|
||
client:
|
||
config:
|
||
default:
|
||
connectTimeout: 5000
|
||
readTimeout: 10000
|
||
loggerLevel: basic
|
||
compression:
|
||
request:
|
||
enabled: true
|
||
response:
|
||
enabled: true
|
||
```
|
||
|
||
### 2. 生产环境配置 (application-pro.yml)
|
||
```yaml
|
||
# 生产环境特定配置
|
||
logging:
|
||
level:
|
||
com.example.{service-name}: INFO
|
||
|
||
feign:
|
||
client:
|
||
config:
|
||
default:
|
||
loggerLevel: basic
|
||
```
|
||
|
||
## 新微服务MongoDB配置
|
||
|
||
### 1. 添加MongoDB依赖
|
||
```xml
|
||
<!-- MongoDB依赖 -->
|
||
<dependency>
|
||
<groupId>org.springframework.boot</groupId>
|
||
<artifactId>spring-boot-starter-data-mongodb</artifactId>
|
||
</dependency>
|
||
```
|
||
|
||
### 2. MongoDB配置类
|
||
```java
|
||
@Configuration
|
||
@EnableMongoRepositories(basePackages = "com.example.{service-name}.repository")
|
||
public class MongoConfig {
|
||
|
||
@Bean
|
||
public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDatabaseFactory) {
|
||
return new MongoTemplate(mongoDatabaseFactory);
|
||
}
|
||
}
|
||
```
|
||
|
||
### 3. MongoDB实体类规范
|
||
```java
|
||
@Document(collection = "collection_name")
|
||
@Data
|
||
public class MongoEntity {
|
||
@Id
|
||
private String id;
|
||
|
||
@Field("field_name")
|
||
private String fieldName;
|
||
|
||
@CreatedDate
|
||
private LocalDateTime createdAt;
|
||
|
||
@LastModifiedDate
|
||
private LocalDateTime updatedAt;
|
||
}
|
||
```
|
||
|
||
### 4. MongoDB Repository规范
|
||
```java
|
||
@Repository
|
||
public interface MongoEntityRepository extends MongoRepository<MongoEntity, String> {
|
||
// 自定义查询方法
|
||
List<MongoEntity> findByFieldName(String fieldName);
|
||
}
|
||
```
|
||
|
||
## 开发规范
|
||
|
||
### 1. 包命名规范
|
||
- 基础包名: `com.example.{service-name}`
|
||
- 服务名使用小写字母和连字符,如: `user-service`, `order-service`
|
||
|
||
### 2. 类命名规范
|
||
- 实体类: 使用名词,如 `User`, `Order`
|
||
- 控制器: 以 `Controller` 结尾,如 `UserController`
|
||
- 服务类: 以 `Service` 结尾,如 `UserService`
|
||
- DTO类: 以 `Request`/`Response` 结尾,如 `UserRequest`, `UserResponse`
|
||
- 常量类: 以 `Constants` 结尾,如 `UserConstants`
|
||
|
||
### 3. 方法命名规范
|
||
- 查询方法: `get`, `find`, `list`, `query`
|
||
- 创建方法: `create`, `add`, `save`
|
||
- 更新方法: `update`, `modify`
|
||
- 删除方法: `delete`, `remove`
|
||
|
||
### 4. 异常处理规范
|
||
- 使用统一的异常处理机制
|
||
- 自定义业务异常继承 `RuntimeException`
|
||
- 使用 `@ControllerAdvice` 进行全局异常处理
|
||
|
||
### 5. 日志规范
|
||
- 使用 `@Slf4j` 注解
|
||
- 日志级别: DEBUG(开发), INFO(生产)
|
||
- 关键操作必须记录日志
|
||
|
||
## 部署配置
|
||
|
||
### 1. Dockerfile规范
|
||
```dockerfile
|
||
FROM registry.bjzgzp.com:4433/library/eclipse-temurin:21-jdk-ubi10-minimal
|
||
|
||
WORKDIR /app
|
||
|
||
COPY ./target/{service-name}.jar /app/{service-name}.jar
|
||
|
||
EXPOSE 8080
|
||
|
||
ENTRYPOINT ["java", "-Djava.net.preferIPv4Stack=true", "-jar", "/app/{service-name}.jar"]
|
||
```
|
||
|
||
### 2. Maven配置
|
||
```xml
|
||
<build>
|
||
<finalName>${project.artifactId}</finalName>
|
||
<plugins>
|
||
<plugin>
|
||
<groupId>org.springframework.boot</groupId>
|
||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||
</plugin>
|
||
<plugin>
|
||
<groupId>org.apache.maven.plugins</groupId>
|
||
<artifactId>maven-surefire-plugin</artifactId>
|
||
<configuration>
|
||
<skipTests>true</skipTests>
|
||
</configuration>
|
||
</plugin>
|
||
<plugin>
|
||
<groupId>org.apache.maven.plugins</groupId>
|
||
<artifactId>maven-compiler-plugin</artifactId>
|
||
<version>3.11.0</version>
|
||
<configuration>
|
||
<source>21</source>
|
||
<target>21</target>
|
||
</configuration>
|
||
</plugin>
|
||
</plugins>
|
||
</build>
|
||
```
|
||
|
||
## 注意事项
|
||
|
||
1. **数据库选择**: 新微服务使用MongoDB 6.x,移除MySQL相关依赖
|
||
2. **版本兼容性**: 确保所有依赖版本与当前项目保持一致
|
||
3. **配置管理**: 使用环境变量管理敏感配置信息
|
||
4. **服务发现**: 使用Nacos进行服务注册与发现
|
||
5. **API文档**: 使用SpringDoc OpenAPI 3生成API文档
|
||
6. **缓存策略**: 使用Redis进行缓存和会话管理
|
||
7. **监控日志**: 集成适当的监控和日志记录机制
|
||
|
||
## 快速开始模板
|
||
|
||
创建新微服务时,可以参考以下步骤:
|
||
|
||
1. 复制当前项目的 `pom.xml`,修改 `artifactId` 和 `name`
|
||
2. 移除MySQL相关依赖,添加MongoDB依赖
|
||
3. 复制项目结构,修改包名
|
||
4. 配置MongoDB连接信息
|
||
5. 创建基础的Controller、Service、Repository
|
||
6. 配置Dockerfile和部署脚本
|
||
|
||
遵循以上规范可以确保新微服务与现有系统保持一致的技术栈和代码风格。
|