Actuator 是 SpringBoot 项目中一个非常强大一个功能,有助于对应用程序进行监视和管理,通过 Restful Api 请求来监管、审计、收集应用的运行情况。
Actuator 的核心是端点 Endpoint,它用来监视应用程序及交互,Spring-Boot-Actuator 目前已经内置了非常多的 Endpoint(health、info、beans、metrics、httptrace、shutdown等等),同时也允许我们自己扩展自己的 Endpoints。每个 Endpoint 都可以启用和禁用。要远程访问 Endpoint,还必须通过 JMX 或 HTTP 进行暴露,大部分应用选择HTTP,Endpoint 的ID默认映射到一个带 /actuator 前缀的URL。例如,Health 端点默认映射到 /actuator/health。
除此,Actuator同时还可以与外部应用监控系统整合,比如 Prometheus, Graphite, DataDog, Influx, Wavefront, New Relic等。这些系统提供了非常好的仪表盘、图标、分析和告警等功能,使得你可以通过统一的接口轻松的监控和管理你的应用。
Actuator使用
启用Actuator功能,最直接的方式是添加 spring-boot-starter-actuator ‘Starter’依赖
1、
pom.xml
<!-- 2、监控 —— Actuator插件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2、
application.yml 或application.properties
management:
endpoints:
# 暴露 EndPoint 以供访问,有jmx和web两种方式,exclude 的优先级高于 include
jmx:
exposure:
exclude: '*'
include: '*'
web:
exposure:
# exclude: '*'
include: ["health","info","beans","mappings","logfile","metrics","shutdown","env"]
base-path: /actuator # 配置 Endpoint 的基础路径
cors: # 配置跨域资源共享
allowed-origins: http://example.com
allowed-methods: GET,POST
enabled-by-default: true # 修改全局 endpoint 默认设置
endpoint:
auditevents: # 1、显示当前引用程序的审计事件信息,默认开启
enabled: true
cache:
time-to-live: 10s # 配置端点缓存响应的时间
beans: # 2、显示一个应用中所有 Spring Beans 的完整列表,默认开启
enabled: true
conditions: # 3、显示配置类和自动配置类的状态及它们被应用和未被应用的原因,默认开启
enabled: true
configprops: # 4、显示一个所有@ConfigurationProperties的集合列表,默认开启
enabled: true
env: # 5、显示来自Spring的 ConfigurableEnvironment的属性,默认开启
enabled: true
flyway: # 6、显示数据库迁移路径,如果有的话,默认开启
enabled: true
health: # 7、显示健康信息,默认开启
enabled: true
show-details: always
info: # 8、显示任意的应用信息,默认开启
enabled: true
liquibase: # 9、展示任何Liquibase数据库迁移路径,如果有的话,默认开启
enabled: true
metrics: # 10、展示当前应用的metrics信息,默认开启
enabled: true
mappings: # 11、显示一个所有@RequestMapping路径的集合列表,默认开启
enabled: true
scheduledtasks: # 12、显示应用程序中的计划任务,默认开启
enabled: true
sessions: # 13、允许从Spring会话支持的会话存储中检索和删除(retrieval and deletion)用户会话。使用Spring Session对反应性Web应用程序的支持时不可用。默认开启。
enabled: true
shutdown: # 14、允许应用以优雅的方式关闭,默认关闭
enabled: true
threaddump: # 15、执行一个线程dump
enabled: true
# web 应用时可以使用以下端点
heapdump: # 16、 返回一个GZip压缩的hprof堆dump文件,默认开启
enabled: true
jolokia: # 17、通过HTTP暴露JMX beans(当Jolokia在类路径上时,WebFlux不可用),默认开启
enabled: true
logfile: # 18、返回日志文件内容(如果设置了logging.file或logging.path属性的话),支持使用HTTP Range头接收日志文件内容的部分信息,默认开启
enabled: true
prometheus: #19、以可以被Prometheus服务器抓取的格式显示metrics信息,默认开启
enabled: true
以简单的项目为例,简要讲解下Actuator功能的相关配置及具体实现,具体如下:
构建完项目后进行启动,应用程序默认以端口8080运行,上图表面程序启动正常,可直接通过Uri访问以获取指定暴露的Endpoints。
通过访问
http://localhost:8080/actuator
来展示所有通过HTTP暴露的Endpoints:
[administrator@JavaLangOutOfMemory java ]% curl 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},"caches-cache":{"href":"http://localhost:8080/actuator/caches/{cache}","templated":true},"caches":{"href":"http://localhost:8080/actuator/caches","templated":false},"health-component":{"href":"http://localhost:8080/actuator/health/{component}","templated":true},"health-component-instance":{"href":"http://localhost:8080/actuator/health/{component}/{instance}","templated":true},"health":{"href":"http://localhost:8080/actuator/health","templated":false},"conditions":{"href":"http://localhost:8080/actuator/conditions","templated":false},"shutdown":{"href":"http://localhost:8080/actuator/shutdown","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},"metrics":{"href":"http://localhost:8080/actuator/metrics","templated":false},"metrics-requiredMetricName":{"href":"http://localhost:8080/actuator/metrics/{requiredMetricName}","templated":true},"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}}}%
打开
http://localhost:8080/actuator/health
,则会显示如下内容:
[administrator@JavaLangOutOfMemory java ]% curl http://localhost:8080/actuator/health
{"status":"UP","details":{"diskSpace":{"status":"UP","details":{"total":100790001664,"free":94206066688,"threshold":10485760}}}}%
请求结果状态若为
UP, 表明应用是健康的。如果应用不健康将会显示DOWN,比如与仪表盘的连接异常或者缺水磁盘空间等。
打开
http://localhost:8080/actuator/metrics
,则会显示如下内容:
[administrator@JavaLangOutOfMemory java ]% curl -i http://localhost:8080/actuator/metrics
HTTP/1.1 200
Content-Type: application/vnd.spring-boot.actuator.v2+json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 10 Jan 2021 01:59:29 GMT
{"names":["jvm.memory.max","jvm.threads.states","process.files.max","jvm.gc.memory.promoted","tomcat.cache.hit","tomcat.servlet.error","system.load.average.1m","tomcat.cache.access","jvm.memory.used","jvm.gc.max.data.size","jvm.gc.pause","jvm.memory.committed","system.cpu.count","logback.events","http.server.requests","tomcat.global.sent","jvm.buffer.memory.used","tomcat.sessions.created","jvm.threads.daemon","system.cpu.usage","jvm.gc.memory.allocated","tomcat.global.request.max","tomcat.global.request","tomcat.sessions.expired","jvm.threads.live","jvm.threads.peak","tomcat.global.received","process.uptime","tomcat.sessions.rejected","process.cpu.usage","tomcat.threads.config.max","jvm.classes.loaded","jvm.classes.unloaded","tomcat.global.error","tomcat.sessions.active.current","tomcat.sessions.alive.max","jvm.gc.live.data.size","tomcat.servlet.request.max","tomcat.threads.current","tomcat.servlet.request","process.files.open","jvm.buffer.count","jvm.buffer.total.capacity","tomcat.sessions.active.max","tomcat.threads.busy","process.start.time"]}%
以下整理了一些非常有用的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
heapdump | 执行一个线程dump
返回一个GZip压缩的JVM堆dump |
Actuator Endpoint解析
/health endpoint
Health Endpoint通过合并几个健康指数检查应用的健康情况。
Spring Boot Actuator有几个预定义的健康指标比如DataSourceHealthIndicator, DiskSpaceHealthIndicator, MongoHealthIndicator, RedisHealthIndicator, CassandraHealthIndicator等。它使用这些健康指标作为健康检查的一部分。
打个比方,如果你的应用使用Redis,RedisHealthindicator将被当作检查的一部分。如果使用MongoDB,那么MongoHealthIndicator将被当作检查的一部分。
你也可以关闭特定的健康检查指标,比如在properties或yml文件中使用如下命令:
management.health.redis.enabled=false
Health Endpoint只展示了简单的UP和DOWN状态。为了获得健康检查中所有指标的详细信息,可以通过在application.yaml中增加如下内容:
management:
endpoint:
health:
show-details: always
当然,如果觉得自带的不能够满足我们的实际业务场景,可以通过实现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", "No!");
}
}
一旦你增加上面的健康指标到你的应用中去后,Health Endpoint将展示如下细节:
{
"status":"UP",
"details":{
"custom":{
"status":"UP",
"details":{
"app":"Alive and Kicking",
"error":"No!"
}
},
"diskSpace":{
"status":"UP",
"details":{
"total":250790436864,
"free":97949245440,
"threshold":10485760
}
}
}
}
Spring Security引入
Actuator Eendpoints是敏感的,必须对其安全性进行可控。如果Spring Security是包含在你的应用中,那么Endpoint是通过HTTP认证被保护起来。
如果没有, 可以增加以下依赖到应用中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
通过以下示例简要展示一个简单的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
至此,Actuator监控功能的讲解到此为止,若您在使用过程中有任何的想法或建议,欢迎留言进行技术交流。