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 {

@Overrideprotected 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. */@Overrideprotected 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#_endpointsrestart:  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 公布