夜雨聆风学习资料网

ARTICLE · 1357274

速查手册实战:常用依赖与注解、配置文件模板、排查命令与故障判断与线上故障排查

速查手册实战:常用依赖与注解、配置文件模板、排查命令与故障判断与线上故障排查

本附录汇总常用配置、注解、命令和排查路径。Spring Boot 3.x 与 Spring Cloud 2023.x/2024.x 为主线,具体配置项随版本变化,使用前以当前版本文档为准。

01

PART

常用依赖

PART 01

...xml

<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>

02

PART

常用注解

PART 02

注解
用途
`@SpringBootApplication`
启动类
`@Configuration`
配置类
`@Bean`
Bean 定义
`@Component`
组件扫描
`@Service`
服务
`@Repository`
数据访问
`@Autowired`
注入
`@Qualifier`
指定候选
`@Primary`
优先候选
`@Value`
注入配置
`@ConfigurationProperties`
配置绑定
`@Transactional`
事务
`@Cacheable`
缓存
`@Scheduled`
调度
`@Async`
异步
`@Valid`
参数校验
`@RestControllerAdvice`
全局异常
`@FeignClient`
HTTP 客户端
`@LoadBalanced`
客户端负载均衡
`@RefreshScope`
刷新作用域

03

PART

配置文件模板

PART 03

...yaml

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

应用配置:

...yaml

app:

downstream:

inventory:

timeout: 2s

retry: 2

feature:

new-order-flow: false

04

PART

Actuator

PART 04

...yaml

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。

05

PART

Web 接口模板

PART 05

...java

@RestController

@RequestMapping("/api/orders")

publicclassOrderController {

@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);

    }

}

全局异常:

...java

@RestControllerAdvice

publicclassApiExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)

@ResponseStatus(HttpStatus.BAD_REQUEST)

public ErrorResponse handleValidation(MethodArgumentNotValidException ex) {

returnnew ErrorResponse("VALIDATION_ERROR", "invalid request");

    }

}

06

PART

事务速查

PART 06

传播行为:

类型
说明
REQUIRED
默认,有则加入,无则新建
REQUIRES_NEW
挂起当前,新建事务
NESTED
保存点嵌套
SUPPORTS
有则加入
NOT_SUPPORTED
挂起并非事务执行
NEVER
有事务则异常
MANDATORY
必须已有事务

失效检查:

...text

自调用?

public 方法?

异常被吞?

rollbackFor?

Bean 被 Spring 管理?

多线程执行?

代理和事务管理器配置正确?

07

PART

Feign 配置

PART 07

...yaml

spring:

cloud:

openfeign:

client:

config:

inventory-service:

connect-timeout: 500

read-timeout: 2000

retryer: never

接口:

...java

@FeignClient(name ="inventory-service", path ="/api/inventories")

publicinterfaceInventoryClient {

@GetMapping("/{id}")

    InventoryView get(@PathVariable Long id);

}

08

PART

Resilience4j

PART 08

...yaml

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

状态:

...text

CLOSED -> OPEN -> HALF_OPEN

09

PART

网关路由

PART 09

...yaml

spring:

cloud:

gateway:

server:

webflux:

routes:

            - id: order

uri: lb://order-service

predicates:

                - Path=/api/orders/**

常用谓词:

...text

Path

Method

Header

Query

Host

Weight

10

PART

Kafka 配置

PART 10

生产者:

...yaml

spring:

kafka:

producer:

bootstrap-servers: kafka:9092

acks: all

properties:

enable.idempotence: true

消费者:

...yaml

spring:

kafka:

consumer:

group-id: order-service

enable-auto-commit: false

治理:

...text

Outbox

幂等表

分区 key

重试 topic

死信 topic

lag 告警

11

PART

测试注解

PART 11

注解
用途
`@SpringBootTest`
完整集成测试
`@WebMvcTest`
Web 切片
`@DataJpaTest`
JPA 切片
`@Testcontainers`
启动容器
`@ServiceConnection`
自动连接测试容器
`@ActiveProfiles`
指定 profile
`@MockBean`
替换 Bean
`@Sql`
执行 SQL

Maven 命令:

...bash

mvn test

mvn verify

12

PART

容器启动参数

PART 12

...bash

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

探针:

...text

/actuator/health/liveness

/actuator/health/readiness

13

PART

优雅停机

PART 13

...properties

server.shutdown=graceful

spring.lifecycle.timeout-per-shutdown-phase=30s

K8s:

...text

terminationGracePeriodSeconds > 应用等待时间

14

PART

排查命令

PART 14

...bash

# 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

日志级别:

...properties

logging.level.org.springframework.web=DEBUG

logging.level.org.springframework.transaction=DEBUG

15

PART

常见故障判断

PART 15

现象
方向
Bean not found
扫描、条件、名字
事务不回滚
自调用、异常、传播
启动慢
Runner、类扫描、CPU
接口慢
SQL、下游、锁、GC
线程池拒绝
下游慢、队列满、流量
OOMKilled
容器总内存
服务找不到
namespace、group、网络
发布 502
摘流和优雅停机
消息重复
至少一次,需幂等
配置不生效
优先级、profile、缩进

回首页,搜索你想要的文档

在首页搜索框输入关键词,快速定位资料

文库首页搜索指引 立即搜索

相关学习资料