一、SpringBoot Actuator
1、简介
SpringBoot 抽取了 Actuator 场景,使得我们每个微服务快速引用即可获得生产级别的应用监控、审计等功能 使用这个场景,首先要引入对应的starter 依赖
< dependency>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter-actuator</ artifactId>
</ dependency>
2、1.x与2.x的不同
3、如何使用
第一步引入Actuator 的依赖,参考上面 第二步通过SpringBoot的核心配置文件,开启指标监控,并以Web的形式暴露
程序默认 JMX 指标监控方式会暴露所有的Endpoint 【cmd -> jconsloe 进入控制台】
# management 是开启 actuator 的配置
management:
endpoints:
enabled-by-default: true # 默认开启所有监控端点
web:
exposure:
include: "*" # 以web的方式暴露所有端点
配置好后,我们就可以开启指标监控的测试了
http: / / localhost: 8080 / actuator/ beans
http: / / localhost: 8080 / actuator/ configprops
http: / / localhost: 8080 / actuator/ metrics
http: / / localhost: 8080 / actuator/ metrics/ jvm. gc. pause
http: / / localhost: 8080 / actuator/ endpointName/ detailPath
4、可视化
在浏览器完成web监控可视化,可以参考下面的这个项目:点击跳转
< dependency>
< groupId> de. codecentric< / groupId>
< artifactId> spring- boot- admin- starter- server< / artifactId>
< version> 2.5 .1 < / version>
< / dependency>
< dependency>
< groupId> org. springframework. boot< / groupId>
< artifactId> spring- boot- starter- web< / artifactId>
< / dependency>
在主程序类上使用 @EnableAdminServer 注解,开启AdminServer监控功能
< dependency>
< groupId> de.codecentric</ groupId>
< artifactId> spring-boot-admin-starter-client</ artifactId>
< version> 2.5.1</ version>
</ dependency>
spring.boot.admin.client.url=http://localhost:8080
management.endpoints.web.exposure.include=*
二、Actuator Endpoint
1、常用端点
端点ID 描述 auditevents 暴露当前应用程序的审核事件信息,需要一个AuditEventRepository组件 beans 显示应用程序中所有Spring Bean的完整列表 caches 暴露可用的缓存 conditions 显示自动配置的所有条件信息,包括匹配或不匹配的原因 configprops 显示所有@ConfigurationProperties env 暴露Spring的属性ConfigurableEnvironment flyway 显示已应用的所有Flyway数据库迁移, 需要一个或多个Flyway组件 health 显示应用程序运行状况信息 httptrace 显示HTTP跟踪信息(默认情况下,最近100个HTTP请求-响应),需要一个HttpTraceRepository组件 info 显示应用程序信息 integrationgraph 显示Spring integrationgraph ,需要依赖spring-integration-core loggers 显示和修改应用程序中日志的配置 liquibase 显示已应用的所有Liquibase数据库迁移,需要一个或多个Liquibase组件 metrics 显示当前应用程序的“指标”信息 mappings 显示所有@RequestMapping路径列表 scheduletasks 显示应用程序中的计划任务 sessions 允许从Spring Session支持的会话存储中检索和删除用户会话,需要使用Spring Session的基于Servlet的Web应用程序 shutdown 使应用程序正常关闭【默认禁用】 startup 显示由ApplicationStartup收集的启动步骤数据。需要使用SpringApplication进行配置BufferingApplicationStartup threaddump 执行线程转储
对于Web应用程序,还可以使用一下附加的端点 【Spring MVC, Spring WebFlux 或 Jersey】
端点ID 描述 heapdump 返回hprof堆转储文件 jolokia 通过HTTP暴露JMX bean(需要引入Jolokia,不适用于WebFlux),需要引入依赖jolokia-core logfile 返回日志文件的内容(如果已设置logging.file.name或logging.file.path属性),支持使用HTTPRange标头来检索部分日志文件的内容 prometheus 以Prometheus服务器可以抓取的格式公开指标,需要依赖micrometer-registry-prometheus
在其中有三个是最常用的端点:
Health:监控状况 Metrics:运行时指标 Loggers:日志记录
2、Health Endpoint
用于云平台的定期应用健康状况检查,可以为平台返回当前应用的一系列组件健康状况的集合 重要的几点信息:
health endpoint 返回的结果,是一些列健康检查后的一个汇总报告 很多的健康检查默认自动配置好了 【例如:Redis、数据库等】 可以很容易的添加自定义的健康检查机制
3、Metrics Endpoint
可以提供详细的、层级的、空间指标信息,这些信息可以被 pull(主动推送)或 push(被动获取)方式得到
通过 Metrics 对接多种监控系统 简化核心 Metrics 开发 添加自定义 Metrics 或者扩展已有 Metrics
4、管理 Endpoints
(1)开启与禁用 Endpoints
默认情况下,所有的端点处了 shutdown 都是开启的 endpoints 是对所有端点的配置信息, endpoint 是对一个端点的配置信息 如果我们需要开启或禁用某个 Endpoint,可以在核心配置文件中进行配置
management.endpoint.<endpointName>.enabled = true / false
我们也可以禁用所有的 Endpoint,然后开启我们需要的 Endpoint
(2)暴露 Endpoints
对于HTTP,默认只暴露 health 和 info 端点(Endpoint) 对于 JMX, 默认暴露所有的端点 除了 health 和 info,剩下的 Endpoint都应该进行保护访问。
如果引入 SpringSecurity ,则会默认配置安全访问规则
ID JMX Web auditevents Yes No beans Yes No caches Yes No conditions Yes No configprops Yes No env Yes No flyway Yes No health Yes Yes heapdump N/A No httptrace Yes No info Yes Yes integrationgraph Yes No jolokia N/A No logfile N/A No loggers Yes No liquibase Yes No metrics Yes No mappings Yes No prometheus N/A No scheduledtasks Yes No sessions Yes No shutdown Yes No startup Yes No threaddump Yes No
三、定制 Endpoint
1、定制 Health 信息
有两种方式:
第一种编写一个类实现我们的 HealthIndicator 接口 第二种编写一个类继承我们的 AbstractHealthIndicator 类 代码演示:
@Component
public class MyComHealthIndicator extends AbstractHealthIndicator {
@Override
protected void doHealthCheck ( Health. Builder builder) throws Exception {
Map < String , Object > map = new HashMap < > ( ) ;
if ( 1 == 2 ) {
builder. status ( Status . UP) ;
map. put ( "count" , 1 ) ;
map. put ( "ms" , 100 ) ;
} else {
builder. status ( Status . OUT_OF_SERVICE) ;
map. put ( "err" , "连接超时" ) ;
map. put ( "ms" , 3000 ) ;
}
builder. withDetail ( "code" , 100 )
. withDetails ( map) ;
}
}
对于 builder.up();
可以替换为 builder.status(Status.UP)
import org. springframework. boot. actuate. health. Health ;
import org. springframework. boot. actuate. health. HealthIndicator ;
import org. springframework. stereotype. Component ;
@Component
public class MyHealthIndicator implements HealthIndicator {
@Override
public Health health ( ) {
int errorCode = check ( ) ;
if ( errorCode != 0 ) {
return Health . down ( ) . withDetail ( "Error Code" , errorCode) . build ( ) ;
}
return Health . up ( ) . build ( ) ;
}
}
构建Health
Health build = Health . down ( )
. withDetail ( "msg" , "error service" )
. withDetail ( "code" , "500" )
. withException ( new RuntimeException ( ) )
. build ( ) ;
management:
health:
enabled: true
show-details: always #总是显示详细信息。可显示每个模块的状态信息
2、定制 info 信息
(1)我们可以采用编写配置文件的方式
info:
appName: boot-admin
version: 2.0.1
mavenProjectName: @project.artifactId@ #使用@@可以获取maven的pom文件值
mavenProjectVersion: @project.version@
(2)编写 InfoContributor
import java. util. Collections ;
import org. springframework. boot. actuate. info. Info ;
import org. springframework. boot. actuate. info. InfoContributor ;
import org. springframework. stereotype. Component ;
@Component
public class ExampleInfoContributor implements InfoContributor {
@Override
public void contribute ( Info. Builder builder) {
builder. withDetail ( "example" ,
Collections . singletonMap ( "key" , "value" ) ) ;
}
}
http://localhost:8080/actuator/info 会输出以上方式返回的所有info信息
3、定制 Metrics 信息
(1)SpringBoot 支持自动适配的 Metrics
JVM metrics, report utilization of:
Various memory and buffer pools Statistics related to garbage collection Threads utilization Number of classes loaded/unloaded CPU metrics File descriptor metrics Kafka consumer and producer metrics Log4j2 metrics: record the number of events logged to Log4j2 at each level Logback metrics: record the number of events logged to Logback at each level Uptime metrics: report a gauge for uptime and a fixed gauge representing the application’s absolute start time Tomcat metrics (server.tomcat.mbeanregistry.enabled must be set to true for all Tomcat metrics to be registered) Spring Integration metrics
(2)增加定制 Metrics
class MyService {
Counter counter;
public MyService ( MeterRegistry meterRegistry) {
counter = meterRegistry. counter ( "myservice.method.running.counter" ) ;
}
public void hello ( ) {
counter. increment ( ) ;
}
}
@Bean
MeterBinder queueSize ( Queue queue) {
return ( registry) -> Gauge . builder ( "queueSize" , queue:: size ) . register ( registry) ;
}
4、定制 Endpoint
@Component
@Endpoint ( id = "container" )
public class DockerEndpoint {
@R ! [ 请添加图片描述] ( https: / / img- blog. csdnimg. cn/ 914 b3ecc5fcb4342a63f1075724a7775. png)
eadOperation
public Map getDockerInfo ( ) {
return Collections . singletonMap ( "info" , "docker started..." ) ;
}
@WriteOperation
private void restartDocker ( ) {
System . out. println ( "docker restarted...." ) ;
}
}
场景:开发ReadinessEndpoint 来管理程序是否就绪,或者LivenessEndpoint 来管理程序是否存活; 当然,这个也可以直接使用 点击跳转