Featured image of post Java 微服务治理:Sentinel 限流降级 + Spring Boot Admin 监控

Java 微服务治理:Sentinel 限流降级 + Spring Boot Admin 监控

部署 Alibaba Sentinel 做流量控制 / 熔断降级 / 系统自适应保护,部署 Spring Boot Admin 做微服务监控告警,docker-compose 集成 + 日志接入 Loki

微服务架构跑起来后,稳定性保障是头等大事——限流、熔断、降级、监控告警缺一不可。本篇把 Alibaba Sentinel 限流和 Spring Boot Admin 监控两套核心组件的 Docker 化部署整理清楚。

阅读对象:Java 后端 / 微服务架构师 覆盖范围:Sentinel Dashboard 部署 + Spring Boot Admin 部署 + 微服务接入 + 限流规则配置 + 告警通知 + Loki 日志集成

一、微服务治理全景

1
2
3
4
5
6
7
8
9
微服务治理体系
  ├─ 服务注册发现:Nacos / Consul / Eureka
  ├─ 配置中心:Nacos / Apollo
  ├─ API 网关:Spring Cloud Gateway / Zuul
  ├─ 服务调用:OpenFeign / Dubbo
  ├─ 服务熔断:Sentinel / Hystrix(已停维)
  ├─ 链路追踪:Sleuth + Zipkin / SkyWalking
  ├─ 监控告警:Spring Boot Admin / Prometheus + Grafana
  └─ 日志聚合:ELK / Loki

本篇聚焦:Sentinel(限流熔断)+ Spring Boot Admin(监控)。

When to use Sentinel

  • 微服务架构,需要防雪崩
  • 双 11、618 大促流量控制
  • 第三方接口调用熔断
  • 秒杀、抢购等高并发场景

When to use Spring Boot Admin

  • Spring Boot 微服务集群监控
  • JVM 指标 / 线程 / 内存 / 日志统一查看
  • 实时健康检查 + 告警

二、Alibaba Sentinel

2.1 简介

Sentinel 是阿里开源的流量控制 / 熔断降级组件,2018 年开源:

维度SentinelHystrix(已停维)Resilience4j
流量控制✅ 多种策略简单简单
熔断降级
系统自适应保护✅(Load / CPU / RT)
控制台✅ 可视化简单
规则持久化✅ Nacos / Apollo / 文件配置中心代码
社区活跃度已停维

2.2 Sentinel Dashboard 部署

下载v1.8.6

1
2
3
4
5
6
7
8
9
# 1. docker 启动
docker run -d --name sentinel --restart=always \
  -p 18080:8080 \
  -v /home/project/safety/sentinel/jar:/jar \
  lwd/jdk:8u371 \
  java -Dserver.port=8080 \
       -Dcsp.sentinel.dashboard.server=localhost:8080 \
       -Dproject.name=sentinel-dashboard \
       -jar /jar/sentinel-dashboard-1.8.6.jar

docker-compose 完整版

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
version: "3"
x-logging: &loki-logging
  driver: loki
  options:
    loki-url: "http://internal.example.com:3100/loki/api/v1/push"
    max-size: "50m"
    max-file: "10"
    loki-pipeline-stages: |
      - multiline:
          firstline: '^\[\d{2}:\d{2}:\d{2} \w{4}\]'
services:
  sentinel:
    image: lwd/jdk:8u371
    container_name: sentinel
    restart: always
    logging: *loki-logging
    network_mode: host
    volumes:
      - "/home/project/safety/sentinel/jar:/jar"
    command: java -Dserver.port=8080 \
                  -Dcsp.sentinel.dashboard.server=localhost:8080 \
                  -Dproject.name=sentinel-dashboard \
                  -jar /jar/sentinel-dashboard-1.8.6.jar

2.3 访问 Dashboard

1
2
http://<IP>:18080
默认账号:sentinel / sentinel

2.4 微服务接入 Sentinel

添加依赖

1
2
3
4
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

配置

1
2
3
4
5
6
7
8
9
spring:
  application:
    name: my-service
  cloud:
    sentinel:
      transport:
        dashboard: localhost:18080    # Sentinel Dashboard 地址
        port: 8719                    # 与 Dashboard 通信端口
      eager: true                     # 启动时立刻注册

限流示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
@RestController
public class OrderController {

    @GetMapping("/order/create")
    @SentinelResource(value = "createOrder", blockHandler = "handleBlock")
    public String createOrder() {
        return "success";
    }

    // 限流后的回调
    public String handleBlock(BlockException e) {
        return "系统繁忙,请稍后重试";
    }
}

2.5 限流规则配置

Dashboard → 簇点链路 → 找到 createOrder流控

1
2
3
4
阈值类型:QPS
单机阈值:100
流控模式:直接
流控效果:快速失败

效果:每秒超过 100 个请求 → 触发限流 → 调用 handleBlock

2.6 熔断降级

Dashboard → 熔断规则

1
2
3
4
5
资源名:createOrder
熔断策略:慢调用比例
最大 RT:500ms
熔断时长:10s
最小请求数:5

效果:5 个请求中慢调用(>500ms)占比超阈值 → 熔断 10s。

2.7 规则持久化(生产必做)

默认规则存内存,重启就丢。生产用 Nacos 持久化:

1
2
3
4
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
spring:
  cloud:
    sentinel:
      datasource:
        ds1:
          nacos:
            server-addr: nacos.internal.example.com:8848
            dataId: sentinel-flow-rules
            groupId: DEFAULT_GROUP
            rule-type: flow

三、Spring Boot Admin

3.1 简介

Spring Boot Admin 是 Spring Boot 应用的统一监控中心

  • 应用健康检查(UP / DOWN / OFFLINE / UNKNOWN)
  • JVM 指标(内存、线程、GC、堆栈)
  • HTTP 请求追踪
  • 日志查看(实时拉取)
  • 配置信息(Spring Environment)
  • 告警通知(邮件 / Slack / PagerDuty / 钉钉 / 飞书)

3.2 创建 Admin Server

pom.xml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-server</artifactId>
    <version>2.5.6</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

Application.java

1
2
3
4
5
6
7
@SpringBootApplication
@EnableAdminServer
public class SpringbootAdminApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootAdminApplication.class, args);
    }
}

application.yml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
server:
  port: 4396
spring:
  application:
    name: springbootadmin
  boot:
    admin:
      notify:
        slack:
          enabled: true
          webhook-url: https://hooks.slack.com/services/{{SLACK_TOKEN}}
        mail:
          enabled: true
          from: noreply@example.com

3.3 部署

1
2
3
4
5
docker run -d --name springbootadmin --restart=always \
  -p 14396:4396 \
  -v /home/docker/springboot-admin/jar:/jar \
  lwd/jdk:8u371 \
  java -jar /jar/SpringbootAdmin-0.0.1-SNAPSHOT.jar
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# docker-compose
version: "3"
x-logging: &loki-logging
  driver: loki
  options:
    loki-url: "http://internal.example.com:3100/loki/api/v1/push"
services:
  admin:
    image: lwd/jdk:8u371
    container_name: admin
    restart: always
    logging: *loki-logging
    network_mode: host
    volumes:
      - "/home/project/safety/admin/jar:/jar"
    command: java -jar /jar/SpringbootAdmin-0.0.1-SNAPSHOT.jar

访问

1
http://<IP>:14396

3.4 微服务注册到 Admin

添加依赖

1
2
3
4
5
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-client</artifactId>
    <version>2.5.6</version>
</dependency>

配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
spring:
  boot:
    admin:
      client:
        url: http://admin.internal.example.com:14396
        instance:
          name: my-service
          prefer-ip: true
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always

重启微服务 → 30 秒后 Admin 后台就能看到这个应用。

3.5 Admin 后台功能

Applications → 点击应用:

  • Details:基本信息
  • Metrics:JVM / 内存 / 线程
  • Environment:配置
  • Logging:实时日志(Level 实时调整
  • JVM:堆栈、线程、GC
  • Mappings:REST API 列表
  • Trace:最近 HTTP 请求
  • Threads:线程详情(可以 dump 堆栈
  • Heapdump:下载堆转储

3.6 告警通知

邮件告警(最常用):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
spring:
  mail:
    host: smtp.example.com
    port: 465
    username: noreply@example.com
    password: {{SMTP_PASS}}
  boot:
    admin:
      notify:
        mail:
          enabled: true
          to:
            - ops-team@example.com
          from: noreply@example.com

Slack 告警

1
2
3
4
5
6
7
8
spring:
  boot:
    admin:
      notify:
        slack:
          enabled: true
          webhook-url: https://hooks.slack.com/services/{{TOKEN}}
          channel: '#alerts'

钉钉告警(自定义 NotificationListener):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@Component
public class DingTalkNotifier implements Notifier {
    @Override
    public void notify(InstanceEvent event) {
        if (event instanceof InstanceStatusChangedEvent) {
            // 调钉钉 Webhook
            sendToDingTalk(((InstanceStatusChangedEvent) event).getInstance().getRegistration().getName());
        }
    }
}

四、限流 vs 监控告警的配合

场景SentinelSpring Boot Admin
应用崩溃熔断防止雪崩告警 + JVM 监控
接口慢慢调用比例熔断Thread dump 分析
流量激增QPS 限流QPS / TPS 指标
内存爆(不管)JVM 内存告警
依赖服务挂熔断下游Health Check 告警

生产推荐两者都上——Sentinel 做"主动防御",Admin 做"被动感知"。

五、典型坑位

5.1 Sentinel Dashboard 看不到应用

修复

1
2
3
4
5
6
spring:
  cloud:
    sentinel:
      transport:
        dashboard: localhost:18080   # 用 IP,不用 localhost
      eager: true                    # 启动时主动注册

触发初始化:访问任意接口(Sentinel 是懒加载,没人调用就不知道有这个接口)。

5.2 限流规则不生效

修复

1
2
3
4
5
// 1. 必须加 @SentinelResource
@SentinelResource(value = "createOrder", blockHandler = "handleBlock")

// 2. 或者用 URL 流控(不推荐)
// Dashboard → 流控规则 → 资源名填 /order/create

5.3 Admin 显示应用 OFFLINE

修复

1
2
3
4
5
6
spring:
  boot:
    admin:
      client:
        instance:
          prefer-ip: true

应用注册到 Admin 时用 IP,不是 hostname

5.4 Admin 看不到日志

修复

1
2
3
4
5
logging:
  file:
    name: /app/logs/myapp.log
  pattern:
    file: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"

日志文件路径必须固定,Admin 才能拉取。

六、生产级架构

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
                            ┌─────────────────┐
                            │  Spring Cloud   │
                            │     Gateway     │
                            └────────┬────────┘
              ┌──────────────────────┼──────────────────────┐
              │                      │                      │
       ┌──────▼──────┐       ┌───────▼──────┐       ┌───────▼──────┐
       │  service-a  │       │  service-b   │       │  service-c   │
       └──────┬──────┘       └───────┬──────┘       └───────┬──────┘
              │                      │                      │
              │    注册信息 + 健康检查 + JVM 指标              │
              └──────────────────────┼──────────────────────┘
                          ┌──────────▼──────────┐
                          │ Spring Boot Admin   │
                          │    Dashboard        │
                          └─────────────────────┘
                          ┌──────────▼──────────┐
                          │    Sentinel         │
                          │    Dashboard        │
                          └─────────────────────┘

所有微服务都做 3 件事

  1. 注册到 Nacos
  2. 监控到 Spring Boot Admin
  3. 限流配置到 Sentinel

七、Spring Boot Admin 高级用法

7.1 日志级别动态调整

Admin 后台 → Logs → 选择 logger → 改 level(如 INFO → DEBUG)。

实时生效,不需要重启应用。

7.2 线程 Dump

Admin 后台 → Threads → Download → 拿 .tdump 文件分析。

典型场景:应用 hang 住时直接 dump 线程看是哪里卡了。

7.3 Heap Dump

Admin 后台 → Heapdump → 下载 .hprof → 用 VisualVM / MAT 分析内存泄漏。

7.4 集成 Spring Security

Admin 后台默认无认证——生产必加:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authz -> authz
                .requestMatchers("/login", "/css/**", "/js/**").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin(Customizer.withDefaults());
        return http.build();
    }
}

八、最佳实践清单

  • Sentinel + Spring Boot Admin 一起上——防御 + 监控双保险
  • Sentinel 规则持久化到 Nacos——重启不丢
  • Admin 后台加 Spring Security——避免被公网访问
  • 限流阈值用真实压测数据——不要拍脑袋
  • 熔断时长 10s 起——给下游恢复时间
  • 告警分级——P0(立即响应)/ P1(小时级)/ P2(日级)
  • 告警去重——同一问题 5 分钟内只发一次
  • 告警值班——on-call 机制,避免"狼来了"
  • JVM 指标进 Prometheus——长期趋势分析
  • 链路追踪进 SkyWalking——慢调用根因分析

2024+ 视角补充

本文写于 2020-06,2024-2026 期间 Java 微服务治理关键演进:

  • Sentinel 1.8.6+ → 1.8.8+(2024-2025):Spring Boot 3.x 兼容JDK 17+ 强制OpenTelemetry 集成——指标 / Trace 全打通
  • Sentinel 2.0 路线图(2025-Q3):AI 限流(基于 LLM 流量预测);自适应并发(自动调整阈值)
  • Spring Boot Admin 3.x(2024-2025):Spring Boot 3.x 兼容Micrometer Tracing 集成;WebFlux 异步应用监控
  • 微服务治理生态(2024-2026):
    • Spring Cloud Alibaba 2023.0+:Nacos 2.x + Sentinel 1.8+ + Seata 1.8+ + RocketMQ 5.x 一站式
    • Spring Cloud 2024+逐步被 Spring Cloud OpenFeign + 独立组件取代——“Spring Cloud 套件"模式弱化
    • Service Mesh(Istio 1.20+ / Linkerd 2.15+)限流 / 熔断下沉到 Sidecar,Java 业务代码不写限流逻辑——2024+ 趋势
    • 可观测三件套:Micrometer + Prometheus + Grafana + Tempo(Trace)——Sentinel 与 OpenTelemetry 融合
  • Spring Cloud Gateway 4.x(2024):Reactor 2024+Spring Cloud LoadBalancer(替代 Ribbon)
  • 云原生时代Spring Boot 3.4+ + K8s 1.30+ + Istio 1.20+ 是 2025+ Java 微服务黄金组合

实战建议(2025-2026 视角)

  • 传统 Spring Cloud 套件Spring Cloud Alibaba 2023.0.x 仍是 2024+ 稳态
  • K8s 上Service Mesh 优先(限流 / 熔断下沉 Sidecar)
  • AI 监控Micrometer + OpenTelemetry + LLM 异常检测(2025+ 实验性)
  • 存量项目 → 升 Spring Boot 3.4+ + JDK 21 是 2025+ 主路线

下一步

使用 Hugo 构建
主题 StackJimmy 设计