这是《Spring Boot 与 Spring Cloud 零基础实战指南》的独立章节版。本章从概念、实操和生产排查三个视角展开,代码块保留了原书可直接运行的版本。 本附录汇总常用配置、注解、命令和排查路径。Spring Boot 3.x 与 Spring Cloud 2023.x/2024.x 为主线,具体配置项随版本变化,使用前以当前版本文档为准。
1. 常用依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway-server-webflux</artifactId>
</dependency>
2. 常用注解
| 注解 | 用途 |
|---|---|
@SpringBootApplication |
启动类 |
@Configuration |
配置类 |
@Bean |
Bean 定义 |
@Component |
组件扫描 |
@Service |
服务 |
@Repository |
数据访问 |
@Autowired |
注入 |
@Qualifier |
指定候选 |
@Primary |
优先候选 |
@Value |
注入配置 |
@ConfigurationProperties |
配置绑定 |
@Transactional |
事务 |
@Cacheable |
缓存 |
@Scheduled |
调度 |
@Async |
异步 |
@Valid |
参数校验 |
@RestControllerAdvice |
全局异常 |
@FeignClient |
HTTP 客户端 |
@LoadBalanced |
客户端负载均衡 |
@RefreshScope |
刷新作用域 |
3. 配置文件模板
spring:
application:
name: order-service
profiles:
active: ${SPRING_PROFILES_ACTIVE:dev}
datasource:
url: jdbc:mysql://${DB_HOST:localhost}:3306/order
username: ${DB_USER:order}
password: ${DB_PASSWORD}
hikari:
pool-name: order-hikari
maximum-pool-size: 20
connection-timeout: 2000
jpa:
open-in-view: false
data:
redis:
host: ${REDIS_HOST:localhost}
timeout: 500ms
应用配置:
app:
downstream:
inventory:
timeout: 2s
retry: 2
feature:
new-order-flow: false
4. Actuator
management:
endpoints:
web:
exposure:
include: health,info,prometheus,metrics
endpoint:
health:
probes:
enabled: true
show-details: never
端点:
| 端点 | 用途 |
|---|---|
/actuator/health |
健康 |
/actuator/health/liveness |
存活 |
/actuator/health/readiness |
就绪 |
/actuator/prometheus |
指标 |
/actuator/conditions |
自动装配报告 |
/actuator/env |
环境配置 |
/actuator/beans |
Bean 信息 |
/actuator/threaddump |
线程 dump |
生产谨慎暴露 env、beans、threaddump。
5. Web 接口模板
@RestController
@RequestMapping("/api/orders")
public class OrderController {
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public OrderView create(@RequestHeader("Idempotency-Key") String key,
@Valid @RequestBody CreateOrderRequest request) {
return orderService.create(request.toCommand(key));
}
@GetMapping("/{id}")
public OrderView get(@PathVariable Long id) {
return orderService.get(id);
}
}
全局异常:
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleValidation(MethodArgumentNotValidException ex) {
return new ErrorResponse("VALIDATION_ERROR", "invalid request");
}
}
6. 事务速查
传播行为:
| 类型 | 说明 |
|---|---|
| REQUIRED | 默认,有则加入,无则新建 |
| REQUIRES_NEW | 挂起当前,新建事务 |
| NESTED | 保存点嵌套 |
| SUPPORTS | 有则加入 |
| NOT_SUPPORTED | 挂起并非事务执行 |
| NEVER | 有事务则异常 |
| MANDATORY | 必须已有事务 |
失效检查:
自调用?
public 方法?
异常被吞?
rollbackFor?
Bean 被 Spring 管理?
多线程执行?
代理和事务管理器配置正确?
7. Feign 配置
spring:
cloud:
openfeign:
client:
config:
inventory-service:
connect-timeout: 500
read-timeout: 2000
retryer: never
接口:
@FeignClient(name = "inventory-service", path = "/api/inventories")
public interface InventoryClient {
@GetMapping("/{id}")
InventoryView get(@PathVariable Long id);
}
8. Resilience4j
resilience4j:
circuitbreaker:
instances:
inventory:
sliding-window-size: 100
minimum-number-of-calls: 20
failure-rate-threshold: 50
wait-duration-in-open-state: 10s
ratelimiter:
instances:
createOrder:
limit-for-period: 100
limit-refresh-period: 1s
状态:
CLOSED -> OPEN -> HALF_OPEN
9. 网关路由
spring:
cloud:
gateway:
server:
webflux:
routes:
- id: order
uri: lb://order-service
predicates:
- Path=/api/orders/**
常用谓词:
Path
Method
Header
Query
Host
Weight
10. Kafka 配置
生产者:
spring:
kafka:
producer:
bootstrap-servers: kafka:9092
acks: all
properties:
enable.idempotence: true
消费者:
spring:
kafka:
consumer:
group-id: order-service
enable-auto-commit: false
治理:
Outbox
幂等表
分区 key
重试 topic
死信 topic
lag 告警
11. 测试注解
| 注解 | 用途 |
|---|---|
@SpringBootTest |
完整集成测试 |
@WebMvcTest |
Web 切片 |
@DataJpaTest |
JPA 切片 |
@Testcontainers |
启动容器 |
@ServiceConnection |
自动连接测试容器 |
@ActiveProfiles |
指定 profile |
@MockBean |
替换 Bean |
@Sql |
执行 SQL |
Maven 命令:
mvn test
mvn verify
12. 容器启动参数
exec java \
-XX:+UseContainerSupport \
-XX:InitialRAMPercentage=60.0 \
-XX:MaxRAMPercentage=60.0 \
-XX:ActiveProcessorCount=4 \
-XX:MaxMetaspaceSize=512m \
-XX:MaxDirectMemorySize=1g \
-Xlog:gc*,safepoint:file=/logs/gc.log:time,uptime,level,tags \
-jar /app/app.jar
探针:
/actuator/health/liveness
/actuator/health/readiness
13. 优雅停机
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=30s
K8s:
terminationGracePeriodSeconds > 应用等待时间
14. 排查命令
# JVM
jcmd <pid> VM.command_line
jcmd <pid> VM.flags
jcmd <pid> Thread.print
jcmd <pid> GC.heap_info
# Linux
top -H -p <pid>
ss -lntp
vmstat 1
日志级别:
logging.level.org.springframework.web=DEBUG
logging.level.org.springframework.transaction=DEBUG
15. 常见故障判断
| 现象 | 方向 |
|---|---|
| Bean not found | 扫描、条件、名字 |
| 事务不回滚 | 自调用、异常、传播 |
| 启动慢 | Runner、类扫描、CPU |
| 接口慢 | SQL、下游、锁、GC |
| 线程池拒绝 | 下游慢、队列满、流量 |
| OOMKilled | 容器总内存 |
| 服务找不到 | namespace、group、网络 |
| 发布 502 | 摘流和优雅停机 |
| 消息重复 | 至少一次,需幂等 |
| 配置不生效 | 优先级、profile、缩进 |