68、微服务保姆教程(十一)微服务的监控与可观测性

三、微服务的监控与可观测性

在微服务架构中,监控与可观测性是确保系统运行健康、排查问题和优化性能的关键。通过收集和分析 metrics 和日志,可以实时了解系统的状态和行为。同时,使用工具如 Sentinel,可以实现更全面的监控和流量控制。本节将详细介绍微服务监控与可观测性的实现方法。


1、Metrics 和日志的收集与分析

Metrics 和日志是监控系统的两大核心要素。通过收集和分析这些数据,可以全面了解系统的运行状态,发现潜在的问题,并及时优化性能。

1. Metrics 的收集与分析

**Metrics(指标)**是用来描述系统或应用程序的各种测量指标,如 CPU 使用率、内存使用情况、HTTP 请求的响应时间等。通过收集和分析这些指标,可以实时监控系统的性能和健康状态。

常见的 Metrics 类型

基础指标(System Metrics)

CPU 使用率
内存使用率
磁盘使用率
网络吞吐量

应用程序指标(Application Metrics)

HTTP 请求的响应时间
并发请求数
错误率
事务成功率

业务指标(Business Metrics)

用户注册数
订单完成数
支付成功率

Metrics 收集工具

Prometheus

简介:Prometheus 是一个开源的系统监控和警报工具。
工作原理:

通过 HTTP 协议拉取目标服务的 metrics 数据。
支持多种数据存储格式,如 OpenMetrics。

优点:灵活性高,支持多种集成。
缺点:配置相对复杂。

Micrometer

简介:Micrometer 是一个为微服务设计的 metrics 收集工具,支持多种监控系统,如 Prometheus、Datadog 等。
优点:易于集成,支持多种数据源。
缺点:功能相对简单,需要配合其他工具使用。

Spring Boot Actuator

简介:Spring Boot Actuator 提供了多种 endpoints 用于监控和管理应用程序,如 /health/metrics 等。
优点:集成简单,提供丰富的监控端点。
缺点:仅适用于 Spring Boot 应用。

示例:使用 Micrometer 和 Prometheus 监控 Spring Boot 应用

pom.xml 中添加依赖:

<dependencies>
    <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-registry-prometheus</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

配置 application.yml,暴露 metrics 端点:

management:
  endpoints:
    web:
      exposure:
        include: "*"
  metrics:
    export:
      prometheus:
        enabled: true

在浏览器中访问 http://localhost:8080/actuator/prometheus,即可获取应用的 metrics 数据。
配置 Prometheus,拉取 metrics 数据并进行监控和告警。

2. 日志的收集与分析

日志记录了系统的运行时信息,是排查问题和优化性能的重要依据。在微服务架构中,由于每个服务可能有自己的日志文件,如何高效地收集和分析这些日志成为一大挑战。

常见的日志收集工具

ELK Stack(Elasticsearch, Logstash, Kibana)

简介:ELK Stack 是一个开源的日志管理平台,支持日志的收集、存储和可视化。
优点:功能强大,支持多种数据源和过滤器。
缺点:资源消耗较高,维护复杂。

Fluentd

简介:Fluentd 是一个数据收集器,支持多种日志格式和存储后端。
优点:轻量级,易于配置。
缺点:功能相对简单。

Graylog

简介:Graylog 是一个开源的日志管理工具,支持日志的收集、存储和分析。
优点:功能全面,支持多种插件。
缺点:资源需求较高。

实现步骤

配置日志框架

使用 Slf4j、Logback 等日志框架,在应用中输出结构化日志。
示例:在 logback-spring.xml 中配置日志格式:

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</Pattern>
        </layout>
    </appender>
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

部署日志收集器

使用 Fluentd 或 Logstash 收集应用日志,并将其发送到 Elasticsearch。

# fluentd.conf
<source>
    @type tail
    path /var/log/app.log
    pos_file /var/log/app.log.pos
    tag app
</source>
<match app.**>
    @type elasticsearch
    host elasticsearch
    port 9200
    index_name fluentd
    type_name log
    logstash_format true
    flush 5
</match>

可视化和分析日志

使用 Kibana 或 Graylog 可视化和分析收集到的日志。
配置仪表盘,监控日志中的错误率、响应时间等指标。

告警与通知

配置告警规则,当日志中出现错误或警告时,自动触发告警并通知相关人员。

# alerting configuration
index: logs-*
query: level: ERROR
condition:
    compare: greater than
    threshold: 5
notify:
    - "email":
        - "admin@example.com"

2、Sentinel 的监控功能

Sentinel 是一个开源的分布式系统保护平台,提供了系统保护、流量控制和实时监控等功能。Sentinel 能够实时记录系统的流量情况,根据预设的规则限制流量,防止系统被过载。

1. Sentinel 的核心功能

流量控制(Flow Control)

根据请求的 QPS(每秒请求数)或线程数设置限制,防止系统因流量过大而崩溃。
支持按接口、按来源等多种粒度的控制。

系统保护(System Protection)

监控系统的负载、响应时间等指标,自动降低进入系统的流量,防止系统过载。
当系统负载过高时,Sentinel 会自动触发保护机制,限制进入的流量。

实时监控(Real-time Monitoring)

提供实时的流量监控,展示系统的 QPS、平均响应时间、接近最大值的资源等信息。
支持查看机器的实时状态,如 CPU 使用率、内存使用率等。

告警与通知(Alerting & Notification)

配置告警规则,当系统达到预设的阈值时,Sentinel 会触发告警并通知相关人员。
支持多种通知方式,如邮件、钉钉等。

2. Sentinel 的安装与配置

步骤

下载与安装

下载 Sentinel Dashboard 的安装包,并解压到指定目录。
或者,使用 Docker 直接运行 Sentinel:

docker run -d -p 8858:8858 -v /tmp/sentinel:/tmp/sentinel bladex/sentinel-dashboard:latest

访问 Sentinel Dashboard

打开浏览器,访问 http://localhost:8858,默认用户名和密码都是 sentinel

配置应用服务

在 Sentinel Dashboard 中,配置需要监控和保护的应用服务。
添加服务的 IP 和端口号,并设置相应的流量控制规则。

curl -X POST 
  http://localhost:8858/api/v1/flow/custom 
  -H 'Content-Type: application/json' 
  -d '{
        "resource": "/api/users",
        "count": 5,
        "unit": "s"
      }'

测试流量控制

使用工具如 JMeter 或 Postman 发送大量请求,观察 Sentinel 是否正确限制了流量。
确保系统在高并发下不会出现服务中断。

3. 在 Spring Boot 中集成 Sentinel

步骤

添加依赖
pom.xml 中添加 Sentinel 的依赖:

<dependencies>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-sentinel-datasource-nacos</artifactId>
    </dependency>
</dependencies>

配置 Sentinel
application.yml 中配置 Sentinel 的相关参数:

spring:
  cloud:
    sentinel:
      enabled: true
      port: 8719
      filter:
        enabled: true
  application:
    name: my-application

启用 Sentinel 注解
在需要控制的接口上添加 @SentinelResource 注解:

@RestController
@RequestMapping("/api/users")
public class UserController {
            
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    @SentinelResource(value = "getUser", blockHandler = "blockUserHandler")
    public User getUser(@PathVariable Long id) {
            
        return userService.getUser(id);
    }

    public User blockUserHandler(Long id, BlockException e) {
            
        return new User(0L, "Unknown", "unknown@example.com");
    }
}

启动应用并测试
启动 Spring Boot 应用,Sentinel 会自动监控和限制流量。
测试高并发请求,观察系统是否按预期限制了流量。


3、总结

微服务的监控与可观测性是确保系统健康和高效运行的重要环节。通过收集和分析 metrics 和日志,可以实时了解系统的状态和性能瓶颈。Sentinel 作为一个强大的流量控制和监控工具,能够帮助开发者保护系统免受过载的影响,并提供实时的监控数据。通过结合这些工具和技术,可以构建一个稳健、可靠和高可用的微服务系统。

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
密林里吃橙子做赢家的头像 - 宋马
评论 抢沙发

请登录后发表评论

    暂无评论内容