Actuator 应用层级的监控与管理

定义

Spring Boot Actuator 是 Spring Boot 提供的一组生产就绪特性,旨在帮助开发者监控和管理 Spring Boot 应用。通过 Actuator,开发者可以轻松获取应用的健康状态、度量指标、应用配置等信息,并且能够通过多种方式(如 HTTP 端点、JMX 等)进行访问和管理。


应用背景

随着微服务架构和云原生应用的普及,监控和管理应用变得尤为重要。传统的应用监控手段往往需要大量的自定义代码和复杂的配置,难以满足快速迭代和高可用性的需求。Spring Boot Actuator 的出现,正是为了解决这一痛点,提供了一套开箱即用的监控与管理工具,使开发者能够专注于业务逻辑的开发,而无需过多关注监控基础设施的搭建。


解决的问题

Spring Boot Actuator 主要解决了以下几个问题:

  1. 健康检查(Health Checks):实时监控应用的健康状态,及时发现潜在问题。
  2. 度量指标(Metrics):收集和展示应用的性能指标,如请求数、响应时间、内存使用等。
  3. 应用信息(Info):展示应用的版本、构建信息等自定义信息。
  4. 环境配置(Environment):查看应用的配置属性,帮助调试和问题排查。
  5. 日志管理(Loggers):动态调整日志级别,便于在运行时进行日志调试。
  6. 线程信息(Thread Dump):获取应用的线程堆栈信息,辅助性能调优和故障诊断。

通过以上功能,Actuator 大大简化了应用的监控与管理工作,提高了开发和运维的效率。


原理

Spring Boot Actuator 基于 Spring Boot 的自动配置机制,通过引入 spring-boot-starter-actuator 依赖,自动注册多个监控端点(Endpoints)。这些端点提供了应用的各类监控信息,并且可以通过配置进行定制和安全控制。

主要原理包括:

  • 自动配置:Actuator 利用 Spring Boot 的自动配置,根据类路径中的依赖和配置属性,自动启用相关的监控端点。
  • 端点暴露:通过 HTTP、JMX 等方式暴露监控端点,默认情况下部分端点仅在特定的环境(如 management.endpoints.web.exposure.include)下可见。
  • 安全控制:集成 Spring Security,提供对监控端点的访问控制,确保只有授权用户才能访问敏感信息。
  • 度量收集:基于 Micrometer 集成,支持多种监控系统(如 Prometheus、Graphite 等)的度量指标收集与导出。

Demo code

以下是一个基于 Spring Boot 3.X 的示例项目,演示如何集成和使用 Actuator 进行应用监控。

1. 创建 Spring Boot 项目

使用 Spring Initializr 创建一个新的 Spring Boot 项目,添加以下依赖:

  • Spring Web
  • Spring Boot Actuator
  • Micrometer Prometheus(用于度量指标导出到 Prometheus)
  • Spring Security(可选,用于保护 Actuator 端点)

2. pom.xml 配置

<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>actuator-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Actuator Demo</name>
    <description>Demo project for Spring Boot Actuator</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <!-- Spring Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Actuator -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!-- Micrometer Prometheus -->
        <dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-registry-prometheus</artifactId>
        </dependency>

        <!-- Spring Security (可选) -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!-- Lombok (可选,用于简化代码) -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- 测试依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Spring Boot Maven Plugin -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

3. 配置文件 application.yml

server:
  port: 8080

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,prometheus,loggers,env,threaddump
  endpoint:
    health:
      show-details: always
  metrics:
    export:
      prometheus:
        enabled: true

spring:
  application:
    name: actuator-demo

4. 主应用类 ActuatorDemoApplication.java

package com.example.actuatordemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ActuatorDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(ActuatorDemoApplication.class, args);
    }

}

5. 创建一个简单的控制器 HelloController.java

package com.example.actuatordemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot Actuator!";
    }
}

6. 自定义应用信息 application.properties 中添加 info 信息

info:
  app:
    version: 1.0.0
    description: "Spring Boot Actuator Demo Application"

7. 配置 Spring Security(可选)

默认情况下,引入 Spring Security 后,所有的 HTTP 端点(包括 Actuator 端点)都需要进行认证。为了简化示例,可以配置一个内存用户。

application.yml 中添加以下配置:

spring:
  security:
    user:
      name: admin
      password: secret

或者,通过 Java 配置自定义安全策略:

package com.example.actuatordemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/**").hasRole("ADMIN")
                .anyRequest().permitAll()
            )
            .httpBasic(Customizer.withDefaults())
            .csrf().disable();
        return http.build();
    }
}

并在 application.yml 中配置用户角色:

spring:
  security:
    user:
      name: admin
      password: secret
      roles: ADMIN

8. 运行应用并访问 Actuator 端点(重点)

启动应用后,可以通过以下 URL 访问不同的 Actuator 端点:

  1. 健康检查: http://localhost:8080/actuator/health
  2. 应用信息: http://localhost:8080/actuator/info
  3. 度量指标: http://localhost:8080/actuator/metrics
  4. Prometheus 指标: http://localhost:8080/actuator/prometheus
  5. 日志管理: http://localhost:8080/actuator/loggers
  6. 环境配置: http://localhost:8080/actuator/env
  7. 线程信息: http://localhost:8080/actuator/threaddump

注意:访问这些端点时,如果启用了 Spring Security,需要提供认证信息(用户名:admin,密码:secret)。

image.png

配合 Prometheus 和 Grafana 进行监控

为了将应用的度量指标导出到 Prometheus,可以使用以下步骤:

  1. 配置 Prometheus

    prometheus.yml 中添加以下配置:

    scrape_configs:
      - job_name: 'spring-actuator'
        metrics_path: '/actuator/prometheus'
        static_configs:
          - targets: ['localhost:8080']
    
    
  2. 启动 Prometheus

    使用 Docker 启动 Prometheus:

    docker run -d -p 9090:9090 -v /path/to/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus
    
    
  1. 配置 Grafana

    • 启动 Grafana(可以使用 Docker)。
    • 在 Grafana 中添加 Prometheus 作为数据源。
    • 导入 Spring Boot Actuator 的预定义仪表盘(例如:Spring Boot Metrics Dashboard)。

通过上述配置,开发者可以在 Grafana 中实时监控 Spring Boot 应用的各类指标,如请求量、响应时间、内存使用、GC 活动等。


小结

Spring Boot Actuator 提供了一套强大且灵活的监控与管理工具,使开发者能够轻松获取和展示应用的运行状态和性能指标。通过与 Micrometer、Prometheus、Grafana 等工具的集成,Actuator 能够在现代微服务和云原生架构中发挥重要作用,帮助团队实现高效的运维和快速的问题诊断。

在实际项目中,开发者可以根据需求自定义 Actuator 端点、扩展度量指标,并结合企业的监控体系,实现全面的应用监控与管理。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,657评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,889评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,057评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,509评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,562评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,443评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,251评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,129评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,561评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,779评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,902评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,621评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,220评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,838评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,971评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,025评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,843评论 2 354

推荐阅读更多精彩内容