• Spring Boot Actuator - Spring Boot 应用监控


    Spring Boot Actuator 使用

    2014年4月,Spring Boot Actuator 与第一个Spring Boot版本一起推出。随着Spring Boot 2的发布,执行器被重新设计,并添加了新的令人兴奋的特性。

    Spring Boot Actuator 为应用程序带来了一些可用于生产环境的特性。如应用监控、收集metrics、数据库状态、JVM监控等等。使用Spring Boot Actuator最大的好处,是通过配置开关轻易的使用生产级别的工具,而不必亲自实现这些功能。Spring Boot Actuator 经常被用于暴露应用系统实时运行信息 - -运行状况、度量、信息、dump、env等。并通过HTTP端点 或者 JMX bean使开发人员能够与其交互。

    只需要增加相关依赖关系,就可以使用endpoints。与大多数Spring模块一样,开发者可以通过多种方式轻松配置或扩展它。

    运行环境

    本项目代码运行环境及原代码信息如下:

    添加Actuator 依赖

    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-actuatorartifactId>
        <version>2.7.5version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Actuator Endpoints

    默认情况下大多数的 endpoint 处于关闭状态,默认只开启 /actuator/health、/actuator/info.两个endpoint。如果想要开启全部endpoint,可以使用如下配置

    management.endpoints.web.exposure.include=*
    
    • 1

    集成Spring Security

    Spring Boot Actuator 与 Spring Security集成时,需要额外增加一些配置。为了调整Actuator 的安全规则,开发者需要添加 /Actuator/ 路径

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(
      ServerHttpSecurity http) {
        return http.authorizeExchange()
          .pathMatchers("/actuator/**").permitAll()
          .anyExchange().authenticated()
          .and().build();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    预定义 Endpoints

    Spring Boot 预定义了很多 Endpoints, 详细信息如下:

    • /auditevents - 罗列出安全审计相关事件,如用户登录/注销. 此外, 还可以按字段进行筛选过滤。
    • /beans - 获取所有的bean信息,不支持过滤。
    • /conditions -构建自动配置条件报告.
    • /configprops - 允许开发者获取所有 @ConfigurationProperties beans.
    • /env - 返回运行环境变量属性.
    • /flyway - 提供有关Flyway数据库迁移的详细信息.
    • /health - 汇总应用系统健康检查状态.
    • /heapdump - dump JVM 文件.
    • /info - 返回系统通用信息,可能是自定义数据、构建信息或有关最新提交的详细信息.
    • /liquibase - 跟/flyway效果一致,但是是Liquibase数据库.
    • /logfile - 返回应用系统日志.
    • /loggers - 查询和修改应用程序的日志记录级别.
    • /metrics - 应用程序 metrics 信息,包含通用 metrics 和自定义metrics .
    • /prometheus - 返回prometheus监控信息.
    • /scheduledtasks - 应用程序中定时任务的详细信息.
    • /sessions – 罗列出使用Spring Session实现的 HTTP sessions 信息.
    • /shutdown – 优化关闭系统.
    • /threaddump – dumps JVM thread 信息.

    Actuator Discovery

    Spring Boot添加了一个发现端点,该端点返回到所有可用执行器endpoint的链接。这将有助于发现执行器endpoint及其对应的URL。默认情况下,该发现 endpoint 可以通过 /actuator 进行访问。如下:

    {
      "_links": {
        "self": {
          "href": "http://localhost:8080/actuator",
          "templated": false
        },
        "features-arg0": {
          "href": "http://localhost:8080/actuator/features/{arg0}",
          "templated": true
        },
        "features": {
          "href": "http://localhost:8080/actuator/features",
          "templated": false
        },
        "beans": {
          "href": "http://localhost:8080/actuator/beans",
          "templated": false
        },
        "caches-cache": {
          "href": "http://localhost:8080/actuator/caches/{cache}",
          "templated": true
        },
        // ...
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    此外,如果开发者配置自定义管理基本路径,name应该使用该基本路径用作发现URL。例如,如果我们设置management.endpoints.web 配置为 /mgmt,那么使用**/mgmt** endpoint 发送一个请求以查看链接列表。

    Health Indicators

    开发者可以很容易地添加自定义指标。与其他API相反,用于创建自定义健康端点的抽象保持不变。但是,添加了一个新的界面,即ReactiveHealthIndicator,以实现反应性健康检查。来看看一个简单的自定义反应式健康检查:

    @Component
    public class DownstreamServiceHealthIndicator implements ReactiveHealthIndicator {
    
        @Override
        public Mono<Health> health() {
            return checkDownstreamServiceHealth().onErrorResume(
              ex -> Mono.just(new Health.Builder().down(ex).build())
            );
        }
    
        private Mono<Health> checkDownstreamServiceHealth() {
            // we could use WebClient to check health reactively
            return Mono.just(new Health.Builder().up().build());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    Health Groups

    从Spring Boot 2.2开始,可以将健康指标进行分组,并将相同的配置应用到组中所有成员。例如,开发者可以在application.properties配置文件中创建一个custom的健康分组

    management.endpoint.health.group.custom.include=diskSpace,ping
    
    • 1

    通过这种方式,custom 分组下包含 磁盘空间、ping 检查相关内容。

    通过访问 /actuator/health endpoint,将会得到以下健康分组信息

    {"status":"UP","groups":["custom"]}
    
    • 1

    也可以单独使用分组名进行访问 /actuator/health/custom ,返回

    {"status":"UP"}
    
    • 1

    可以在application.properties配置文件中配置显示分组详细信息

    management.endpoint.health.group.custom.show-components=always
    management.endpoint.health.group.custom.show-details=always
    
    • 1
    • 2

    同样访问***/actuator/health/custom***,将得到更加详细的信息

    {
      "status": "UP",
      "components": {
        "diskSpace": {
          "status": "UP",
          "details": {
            "total": 499963170816,
            "free": 91300069376,
            "threshold": 10485760
          }
        },
        "ping": {
          "status": "UP"
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    配置详细信息只针对授权用户查看

    management.endpoint.health.group.custom.show-components=when_authorized
    management.endpoint.health.group.custom.show-details=when_authorized
    
    • 1
    • 2

    此外,可以定制HTTP 返回状态码,配置状态码为 207 返回

    management.endpoint.health.group.custom.status.http-mapping.up=207
    
    • 1

    Metrics

    Spring Boot 2 支持毫秒级别的指标监控,并为开发者自动配置 MeterRegistry bean。开发者可以通过 /metrics 路径,得到相关信息:

    {
      "names": [
        "jvm.gc.pause",
        "jvm.buffer.memory.used",
        "jvm.memory.used",
        "jvm.buffer.count",
        // ...
      ]
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    通过指定目标值,获取更加详细的信息,如 /actuator/metrics/jvm.gc.pause

    {
      "name": "jvm.gc.pause",
      "measurements": [
        {
          "statistic": "Count",
          "value": 3.0
        },
        {
          "statistic": "TotalTime",
          "value": 7.9E7
        },
        {
          "statistic": "Max",
          "value": 7.9E7
        }
      ],
      "availableTags": [
        {
          "tag": "cause",
          "values": [
            "Metadata GC Threshold",
            "Allocation Failure"
          ]
        },
        {
          "tag": "action",
          "values": [
            "end of minor GC",
            "end of major GC"
          ]
        }
      ]
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    定制 Info Endpoint

    开发者可以为Info Endpoint 增加额外的信息

    <dependency>
        <groupId>pl.project13.mavengroupId>
        <artifactId>git-commit-id-pluginartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4

    同样,我们也可以使用Maven或Gradle插件包含构建信息,包括名称、组和版本:

    <plugin>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-maven-pluginartifactId>
        <executions>
            <execution>
                <goals>
                    <goal>build-infogoal>
                goals>
            execution>
        executions>
    plugin>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在浏览器输入地址: http://localhost:8081/actuator/info

    {
    	"build": {
    		"artifact": "spring-boot-admin-client",
    		"name": "spring-boot-admin-client",
    		"time": "2022-11-23T13:58:58.489Z",
    		"version": "0.0.1-SNAPSHOT",
    		"group": "com.andy.spring.boot.admin"
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    自定义Endpoint

    Spring Boot 2重新设计了实现自定义Endpoint的方法。下面构建一个自定义的endpoint,并支持查询、启用、禁用特性。

    @Component
    @Endpoint(id = "features")
    public class FeaturesEndpoint {
    
        private Map<String, Feature> features = new ConcurrentHashMap<>();
    
        @ReadOperation
        public Map<String, Feature> features() {
            return features;
        }
    
        @ReadOperation
        public Feature feature(@Selector String name) {
            return features.get(name);
        }
    
        @WriteOperation
        public void configureFeature(@Selector String name, Feature feature) {
            features.put(name, feature);
        }
    
        @DeleteOperation
        public void deleteFeature(@Selector String name) {
            features.remove(name);
        }
    
        public static class Feature {
            private Boolean enabled;
    
            // [...] getters and setters 
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    上述代码可以通过**/actuator/features**进行访问,不同的方法需要不同的访问方式:

    • @ReadOperation: It’ll map to HTTP GET.
    • @WriteOperation: It’ll map to HTTP POST.
    • @DeleteOperation: It’ll map to HTTP DELETE.

    扩展存在的Endpoints

    假设一种应用场景:我们希望确保应用程序的生产实例永远不是SNAPSHOT版本。我们决定通过更改返回此信息的执行器端点的HTTP状态代码(即/info)来完成此操作。如果我们的应用程序恰好是SNAPSHOT,我们将得到不同的HTTP状态代码。

    @Component
    @EndpointWebExtension(endpoint = InfoEndpoint.class)
    public class InfoWebEndpointExtension {
    
        private InfoEndpoint delegate;
    
        // standard constructor
    
        @ReadOperation
        public WebEndpointResponse<Map> info() {
            Map<String, Object> info = this.delegate.info();
            Integer status = getStatus(info);
            return new WebEndpointResponse<>(info, status);
        }
    
        private Integer getStatus(Map<String, Object> info) {
            // return 5xx if this is a snapshot
            return 200;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    启用所有Endpoint

    为了使用HTTP接口访问Endpoints信息,开发者需要手动启用、暴露它们。默认情况下,除了 /shutdown 之外的所有 endpoint都是启用的。但是仅暴露 /health /info 两个endpoints。

    暴露所有endpoints

    management.endpoints.web.exposure.include=*
    
    • 1

    暴露特殊的endpoint,如 /shutdown

    management.endpoint.shutdown.enabled=true
    
    • 1

    暴露所有的endpoints,除了 /logger

    management.endpoints.web.exposure.include=*
    management.endpoints.web.exposure.exclude=loggers
    
    • 1
    • 2
  • 相关阅读:
    电脑重装系统还原0x80070005错误如何解决
    全栈项目【尚医通】预约挂号系统项目介绍
    Visual Studio 2019 + LibTorch + CUDA11.6 环境配置
    使用 Java RestClient 与 Elasticsearch 进行索引管理的示例
    《web课程设计》基于HTML+CSS+JavaScript典的中医药大学网(11个页面)
    投资的思考
    EtherCAT从站EEPROM分类附加信息详解:FMMU(现场总线内存管理单元)
    SpringWeb(SpringMVC)
    xxl-job 快速使用
    初识Canal以及使用Docker安装配置
  • 原文地址:https://blog.csdn.net/u013433591/article/details/128025720