关于java:Spring-Boot-Actuator健康检查审计统计和监控

5次阅读

共计 11172 个字符,预计需要花费 28 分钟才能阅读完成。

Spring Boot Actuator 能够帮忙你监控和治理 Spring Boot 利用,比方健康检查、审计、统计和 HTTP 追踪等。所有的这些个性能够通过 JMX 或者 HTTP endpoints 来取得。

Actuator 同时还能够与内部利用监控零碎整合,比方 Prometheus, Graphite, DataDog, Influx, Wavefront, New Relic 等。这些零碎提供了十分好的仪表盘、图标、剖析和告警等性能,使得你能够通过对立的接口轻松的监控和治理你的利用。

Actuator 应用 Micrometer 来整合下面提到的内部利用监控零碎。这使得只有通过十分小的配置就能够集成任何利用监控零碎。

我将把 Spring Boot Actuator 教程分为两局部:

第一局部 (本文) 教你如何配置 Actuator 和通过 Http endpoints 来进入这些特色。
第二局部教你如何整合 Actuator 和内部利用监控零碎。
创立一个有 Actuator 的 Spring Boot 工程
你能够减少 spring-boot-actuator 模块到一个曾经存在的利用,通过应用上面的依赖。

<dependencies>
<dependency>

<groupId>org.springframework.boot</groupId>        
<artifactId>spring-boot-starter-actuator</artifactId>    

</dependency>
</dependencies>
应用 Actuator Endpoints 来监控利用
Actuator 创立了所谓的 endpoint 来裸露 HTTP 或者 JMX 来监控和治理利用。

举个例子,有一个叫 /health 的 endpoint,提供了对于利用衰弱的根底信息。/metricsendpoints 展现了几个有用的度量信息,比方 JVM 内存应用状况、零碎 CPU 应用状况、关上的文件等等。/loggersendpoint 展现了利用的日志和能够让你在运行时扭转日志等级。

值得注意的是,每一给 actuator endpoint 能够被显式的关上和敞开。此外,这些 endpoints 也须要通过 HTTP 或者 JMX 裸露进去,使得它们能被近程进入。

让咱们运行利用并且尝试进入默认通过 HTTP 裸露的关上状态的 actuator endpoints。之后,咱们将学习如何关上更多的 endpoints 并且通过 HTTP 裸露它们。

在利用的根目录下关上命令行工具运行以下命令:

mvn spring-boot:run

利用默认应用 8080 端口运行。一旦这个利用启动了,你能够通 http://localhost:8080/actuator 来展现所有通过 HTTP 裸露的 endpoints。

{“_links”:{“self”:{“href”:”http://localhost:8080/actuator”,”templated”:false},”health”:{“href”:”http://localhost:8080/actuator/health”,”templated”:false},”info”:{“href”:”http://localhost:8080/actuator/info”,”templated”:false}}}
关上 http://localhost:8080/actuator/health,则会显示如下内容:

{“status”:”UP”}
状态将是 UP 只有利用是衰弱的。如果利用不衰弱将会显示 DOWN, 比方与仪表盘的连贯异样或者缺水磁盘空间等。下一节咱们将学习 spring boot 如何决定利用的衰弱和如何修复这些衰弱问题。

infoendpoint(http://localhost:8080/actuator/info)展现了对于利用的个别信息,这些信息从编译文件比方 META-INF/build-info.properties 或者 Git 文件比方 git.properties 或者任何环境的 property 中获取。你将在下一节中学习如何扭转这个 endpoint 的输入。

默认,只有 health 和 info 通过 HTTP 裸露了进去。这也是为什么 /actuator 页面只展现了 health 和 infoendpoints。咱们将学习如何裸露其余的 endpoint。首先,让咱们看看其余的 endpoints 是什么。

以下是一些十分有用的 actuator endpoints 列表。你能够在 official documentation 下面看到残缺的列表。

Endpoint ID Description
auditevents 显示利用裸露的审计事件 (比方认证进入、订单失败)
info 显示利用的根本信息
health 显示利用的衰弱状态
metrics 显示利用多样的度量信息
loggers 显示和批改配置的 loggers
logfile 返回 log file 中的内容(如果 logging.file 或者 logging.path 被设置)
httptrace 显示 HTTP 脚印,最近 100 个 HTTP request/repsponse
env 显示以后的环境个性
flyway 显示数据库迁徙门路的详细信息
liquidbase 显示 Liquibase 数据库迁徙的细微信息
shutdown 让你逐渐敞开利用
mappings 显示所有的 @RequestMapping 门路
scheduledtasks 显示利用中的调度工作
threaddump 执行一个线程 dump
heapdump 返回一个 GZip 压缩的 JVM 堆 dump
关上和敞开 Actuator Endpoints
默认,上述所有的 endpints 都是关上的,除了 shutdown endpoint。

你能够通过设置 management.endpoint.<id>.enabled to true or false(id 是 endpoint 的 id)来决定关上还是敞开一个 actuator endpoint。

举个例子,要想关上 shutdown endpoint,减少以下内容在你的 application.properties 文件中:

management.endpoint.shutdown.enabled=true
裸露 Actuator Endpoints
默认,素偶偶的 actuator endpoint 通过 JMX 被裸露,而通过 HTTP 裸露的只有 health 和 info。

以下是你能够通过利用的 properties 能够通过 HTTP 和 JMX 裸露的 actuator endpoint。

通过 HTTP 裸露 Actuator endpoints。

Use “*” to expose all endpoints, or a comma-separated list to expose selected onesmanagement.endpoints.web.exposure.include=health,info management.endpoints.web.exposure.exclude=

通过 JMX 裸露 Actuator endpoints。

Use “” to expose all endpoints, or a comma-separated list to expose selected onesmanagement.endpoints.jmx.exposure.include=management.endpoints.jmx.exposure.exclude=

通过设置 management.endpoints.web.exposure.include 为 *,咱们能够在 http://localhost:8080/actuator 页面看到如下内容。

{“_links”:{“self”:{“href”:”http://localhost:8080/actuator”,”templated”:false},”auditevents”:{“href”:”http://localhost:8080/actuator/auditevents”,”templated”:false},”beans”:{“href”:”http://localhost:8080/actuator/beans”,”templated”:false},”health”:{“href”:”http://localhost:8080/actuator/health”,”templated”:false},”conditions”:{“href”:”http://localhost:8080/actuator/conditions”,”templated”:false},”configprops”:{“href”:”http://localhost:8080/actuator/configprops”,”templated”:false},”env”:{“href”:”http://localhost:8080/actuator/env”,”templated”:false},”env-toMatch”:{“href”:”http://localhost:8080/actuator/env/{toMatch}”,”templated”:true},”info”:{“href”:”http://localhost:8080/actuator/info”,”templated”:false},”loggers”:{“href”:”http://localhost:8080/actuator/loggers”,”templated”:false},”loggers-name”:{“href”:”http://localhost:8080/actuator/loggers/{name}”,”templated”:true},”heapdump”:{“href”:”http://localhost:8080/actuator/heapdump”,”templated”:false},”threaddump”:{“href”:”http://localhost:8080/actuator/threaddump”,”templated”:false},”prometheus”:{“href”:”http://localhost:8080/actuator/prometheus”,”templated”:false},”metrics-requiredMetricName”:{“href”:”http://localhost:8080/actuator/metrics/{requiredMetricName}”,”templated”:true},”metrics”:{“href”:”http://localhost:8080/actuator/metrics”,”templated”:false},”scheduledtasks”:{“href”:”http://localhost:8080/actuator/scheduledtasks”,”templated”:false},”httptrace”:{“href”:”http://localhost:8080/actuator/httptrace”,”templated”:false},”mappings”:{“href”:”http://localhost:8080/actuator/mappings”,”templated”:false}}}
解析罕用的 actuator endpoint
/health endpoint
health endpoint 通过合并几个衰弱指数查看利用的衰弱状况。

Spring Boot Actuator 有几个预约义的衰弱指标比方 DataSourceHealthIndicator, DiskSpaceHealthIndicator, MongoHealthIndicator, RedisHealthIndicator, CassandraHealthIndicator 等。它应用这些衰弱指标作为健康检查的一部分。

举个例子,如果你的利用应用 Redis,RedisHealthindicator 将被当作查看的一部分。如果应用 MongoDB,那么 MongoHealthIndicator 将被当作查看的一部分。

你也能够敞开特定的健康检查指标,比方在 prpperties 中应用如下命令:

management.health.mongo.enabled=false
默认,所有的这些衰弱指标被当作健康检查的一部分。

显示具体的衰弱信息
health endpoint 只展现了简略的 UP 和 DOWN 状态。为了取得健康检查中所有指标的详细信息,你能够通过在 application.yaml 中减少如下内容:

management:
endpoint:

 health:      
   show-details: always

一旦你关上上述开关,你在 /health 中能够看到如下具体内容:

{“status”:”UP”,”details”:{“diskSpace”:{“status”:”UP”,”details”:{“total”:250790436864,”free”:27172782080,”threshold”:10485760}}}}
health endpoint 当初蕴含了 DiskSpaceHealthIndicator。

如果你的利用蕴含 database(比方 MySQL),health endpoint 将显示如下内容:

{

"status": "UP",
"details": {
    "db": {
        "status": "UP",
        "details": {
            "database": "MySQL",
            "hello": 1
        }
    },
    "diskSpace": {
        "status": "UP",
        "details": {
            "total": 250790436864,
            "free": 100330897408,
            "threshold": 10485760
        }
    }
}

}
如果你的 MySQL server 没有启起来,状态将会变成 DOWN:

{

"status": "DOWN",
"details": {
    "db": {
        "status": "DOWN",
        "details": {"error": "org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30006ms."}
    },
    "diskSpace": {
        "status": "UP",
        "details": {
            "total": 250790436864,
            "free": 100324585472,
            "threshold": 10485760
        }
    }
}

}
创立一个自定义的衰弱指标
你能够通过实现 HealthIndicator 接口来自定义一个衰弱指标,或者继承 AbstractHealthIndicator 类。

package com.example.actuator.health;

import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.stereotype.Component;

@Component
public class CustomHealthIndicator extends AbstractHealthIndicator {

@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
    // Use the builder to build the health status details that should be reported.
    // If you throw an exception, the status will be DOWN with the exception message.
    
    builder.up()
            .withDetail("app", "Alive and Kicking")
            .withDetail("error", "Nothing! I'm good.");
}

}

一旦你减少下面的衰弱指标到你的利用中去后,health endpoint 将展现如下细节:

{
“status”:”UP”,
“details”:{

  "custom":{
     "status":"UP",
     "details":{
        "app":"Alive and Kicking",
        "error":"Nothing! I'm good."
     }
  },
  "diskSpace":{
     "status":"UP",
     "details":{
        "total":250790436864,
        "free":97949245440,
        "threshold":10485760
     }
  }

}
}

/metrics endpoint
metrics endpoint 展现了你能够追踪的所有的度量。

{
“names”: [

  "jvm.memory.max",
  "http.server.requests",
  "process.files.max",
  ...
  "tomcat.threads.busy",
  "process.start.time",
  "tomcat.servlet.error"

]
}
想要取得每个度量的详细信息,你须要传递度量的名称到 URL 中,像

http://localhost:8080/actuator/metrics/{MetricName}

举个例子,取得 systems.cpu.usage 的详细信息,应用以下 URLhttp://localhost:8080/actuator/metrics/system.cpu.usage。它将显示如下内容:

{
“name”: “system.cpu.usage”,
“measurements”: [
{

  "statistic": "VALUE",
  "value": 0

}
],
“availableTags”: []
}

/loggers endpoint
loggers endpoint,能够通过拜访 http://localhost:8080/actuator/loggers 来进入。它展现了利用中可配置的 loggers 的列表和相干的日志等级。

你同样可能应用 http://localhost:8080/actuator/loggers/{name}来展现特定 logger 的细节。

举个例子,为了取得 root logger 的细节,你能够应用 http://localhost:8080/actuator/loggers/root:

{

 "configuredLevel":"INFO",  
 "effectiveLevel":"INFO"

}
在运行时扭转日志等级
loggers endpoint 也容许你在运行时扭转利用的日志等级。

举个例子,为了扭转 root logger 的等级为 DEBUG,发送一个 POST 申请到 http://localhost:8080/actuator/loggers/root,退出如下参数

{“configuredLevel”: “DEBUG”}
这个性能对于线上问题的排查十分有用。

同时,你能够通过传递 null 值给 configuredLevel 来重置日志等级。

/info endpoint
info endpoint 展现了利用的根本信息。它通过 META-INF/build-info.properties 来取得编译信息,通过 git.properties 来取得 Git 信息。它同时能够展现任何其余信息,只有这个环境 property 中含有 infokey。

你能够减少 properties 到 application.yaml 中,比方:

INFO ENDPOINT CONFIGURATION

info:
app:

name: @project.name@
description: @project.description@
version: @project.version@
encoding: @project.build.sourceEncoding@
java:
  version: @java.version@

留神,我应用了 Spring Boot 的 Automatic property expansion 特色来扩大来自 maven 工程的 properties。

一旦你减少下面的 properties,info endpoint 将展现如下信息:

{
“app”: {
“name”: “actuator”,
“description”: “Demo project for Spring Boot”,
“version”: “0.0.1-SNAPSHOT”,
“encoding”: “UTF-8”,
“java”: {

  "version": "1.8.0_161"
  }

}
}
应用 Spring Security 来保障 Actuator Endpoints 平安
Actuator endpoints 是敏感的,必须保障进入是被受权的。如果 Spring Security 是蕴含在你的利用中,那么 endpoint 是通过 HTTP 认证被爱护起来的。

如果没有,你能够减少以下以来到你的利用中去:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency
接下去让咱们看一下如何覆写 spring security 配置,并且定义你本人的进入规定。

上面的例子展现了一个简略的 spring securiy 配置。它应用叫做 EndPointRequest

的 ReqeustMatcher 工厂模式来配置 Actuator endpoints 进入规定。

package com.example.actuator.config;

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.context.ShutdownEndpoint;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {

/*
    This spring security configuration does the following

    1. Restrict access to the Shutdown endpoint to the ACTUATOR_ADMIN role.
    2. Allow access to all other actuator endpoints.
    3. Allow access to static resources.
    4. Allow access to the home page (/).
    5. All other requests need to be authenticated.
    5. Enable http basic authentication to make the configuration complete.
       You are free to use any other form of authentication.
 */

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .requestMatchers(EndpointRequest.to(ShutdownEndpoint.class))
                    .hasRole("ACTUATOR_ADMIN")
                .requestMatchers(EndpointRequest.toAnyEndpoint())
                    .permitAll()
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations())
                    .permitAll()
                .antMatchers("/")
                    .permitAll()
                .antMatchers("/**")
                    .authenticated()
            .and()
            .httpBasic();}

}
为了可能测试以上的配置,你能够在 application.yaml 中减少 spring security 用户。

Spring Security Default user name and password

spring:
security:

user:
  name: actuator
  password: actuator
  roles: ACTUATOR_ADMIN

留神问题:

Spring Boot 1.x 和 Spring Boot 2.x 配置不同

Spring Boot 2.x
management:
endpoint:

# 启用 pause 端点
pause:
  enabled: true
# 启用 restart 端点,之所以要启用 restart 端点,是因为 pause 端点的启用依赖 restart 端点的启用。详见:https://cloud.spring.io/spring-cloud-static/Finchley.SR2/single/spring-cloud.html#_endpoints
restart:
  enabled: true

endpoints:

web:
  exposure:
    include: pause,restart

Spring Boot 1.x
endpoints:

# 启用 pause 端点
pause:
  enabled: true
# 启用 restart 端点,之所以要启用 restart 端点,是因为 pause 端点的启用依赖 restart 端点的启用
restart:
  enabled: true

须要留神的是,Spring Boot 2.x 的端点根底门路由 / 调整到 /actuator 下,如:/info 调整为 /actuator/info 能够通过以下配置改为和旧版本统一:

management.endpoints.web.base-path=/

参考链接
https://blog.csdn.net/u010629…

https://bigjar.github.io/2018…

本文由博客群发一文多发等经营工具平台 OpenWrite 公布

正文完
 0