目录
提前预知
- 课程笔记来源于雷神的SpringBoot2教程
- 参考文档地址:参考文档
- 要学会查看官方文档!!!!!!!!!
01、SpringBoot Actuator
1.1、简介
每一个微服务在云上部署以后,我们都需要对其进行监控、追踪、审计、控制等。SpringBoot就抽取了Actuator场景,使得我们每个微服务快速引用即可获得生产级别的应用监控、审计等功能。
- 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- SpringBoot1.x 和 SpringBoot2.x中
Actuator的对比
:
1.2、如何使用
- 第一步:引入场景依赖
- 第二步:访问链接:
http://localhost:8080/actuator/**
- 第三步:暴露所有监控信息为HTTP,在配置文件中配置
management:
endpoints: # 所有端点的配置
enabled-by-default: true #暴露所有端点信息
web:
exposure:
include: '*' #以web方式暴露
endpoint: #对某个端点的具体配置
health:
show-details: always
enabled: true
info:
enabled: true
beans:
enabled: true
metrics:
enabled: true
- 第四步:配置之后进行测试,挑几个进行测试,具体的可以参考官方文档
查看容器中的bean报告:
http://localhost:8080/actuator/beans
查看bean配置属性报告:
http://localhost:8080/actuator/configprops
查看自动配置报告:http://localhost:8080/actuator/conditions
指标监控:
http://localhost:8080/actuator/metrics
例如:http://localhost:8080/actuator/metrics/jvm.gc.pause
http://localhost:8080/actuator/endpointName/detailPath
注意:
- 在SpringBoot中
默认
暴露断点的方式都是一JMX方式,Web方式暴露的就一个,可以在官方文档的5.2. Endpoints
这个章节查看,部分截图如下:
- 还是之前分析的套路,如果想要知道这些东西被怎么被SpringBoot自动配置进来的,就要分析相关的
自动配置类
,想要知道为什么在配置文件中那样配置,就要查看和配置类绑定的属性类
。
1.3、可视化(挺有意思的)
监控可视化功能项目Github地址:https://github.com/codecentric/spring-boot-admin
- 点击进入Github:
如何使用(参考参考文档):
- 第一步:创建一个SpringBoot的项目,作为
监控项目
- 第二步:在监控项目中导入依赖
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 第三步:在
监控的项目
的主配置类上添加注解:@EnableAdminServer
- 第四步:在设置
监控项目
的启动端口号,不要与其他项目冲突即可,例如:8888 - 第五步:在
被监控项目
中引入依赖
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.3.1</version>
</dependency>
- 第六步:在
被监控的项目
上配置监控的客户端(监控项目的地址),以及暴露端点
spring.boot.admin.client.url=http://localhost:8888
management.endpoints.web.exposure.include=*
spring:
boot:
admin:
client: # 设置监控客户端
url: http://localhost:8888
instance:
prefer-ip: true #使用ip注册进来
application:
name: boot-05-web-admin # 项目名字
- 第七步:启动两个项目,访问
http://localhost:8888
02、Actuator Endpoint
2.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路径列表。 |
scheduledtasks | 显示应用程序中的计划任务。 |
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。 |
最常用的Endpoint
Health
:监控状况Metrics
:运行时指标Loggers
:日志记录
2.2、Health Endpoint
健康检查端点,我们一般用于在云平台,平台会定时的检查应用的健康状况,我们就需要Health Endpoint可以为平台返回当前应用的一系列组件健康状况的集合。
重要的几点:
- health endpoint返回的结果,应该是一系列健康检查后的一个汇总报告
- 很多的健康检查默认已经自动配置好了,比如:数据库、redis等
- 可以很容易的添加自定义的健康检查机制
注意:如果感觉一个端点的显示信息不是那么的详细,我们也可以在配置文件中进行详细配置
:
management:
endpoint: #对某个端点的具体配置
health:
show-details: always
enabled: true
info:
enabled: true
beans:
enabled: true
metrics:
enabled: true
2.3、Metrics Endpoint
提供详细的、层级的、空间指标信息,这些信息可以被pull(主动推送)或者push(被动获取)方式得到;
- 通过Metrics对接多种监控系统
- 简化核心Metrics开发
- 添加自定义Metrics或者扩展已有Metrics
2.4、管理Endpoints
开启与禁用Endpoints
- 默认所有的Endpoint除过shutdown都是开启的。
- 需要开启或者禁用某个Endpoint,配置模式为 :
management.endpoint.<endpointName>.enabled = true
management:
endpoint:
beans: #以bean端点为例
enabled: true
- 或者禁用所有的Endpoint然后手动开启指定的Endpoint
management:
endpoints:
enabled-by-default: false
endpoint:
beans:
enabled: true
health:
enabled: true
暴露Endpoints
支持的暴露方式:
- HTTP:默认只暴露
health
和info
端点 - JMX:默认暴露
所有
端点 - 除过health和info,剩下的Endpoint都应该进行保护访问。如果引入SpringSecurity,则会默认配置安全访问规则
03、定制 Endpoints
如果有些我们需要的监控信息,默认里面没有监控,我们可以进行自定义
例如:我们想监控某个组件的健康信息,默认里面没有的,我们可以自定义
如何定制那,肯定是比葫芦画瓢,我们以health端点
为例:
- 打开actuator的自动配置包,找到有关health的自动配置包
- 找到自动配置类
:HealthContributorAutoConfiguration
@Configuration(proxyBeanMethods = false)
public class HealthContributorAutoConfiguration {
public HealthContributorAutoConfiguration() {
}
@Bean
@ConditionalOnEnabledHealthIndicator("ping")
public PingHealthIndicator pingHealthContributor() {
//返回一个这个类的实例
return new PingHealthIndicator();
}
}
//继承这个抽象类
public class PingHealthIndicator extends AbstractHealthIndicator {
public PingHealthIndicator() {
}
//重写抽象方法
protected void doHealthCheck(Builder builder) throws Exception {
//使用Builder的实例返回值
builder.up();
}
}
- 其他的端点也是类似方法
3.1、定制 Health 信息
- 自定义监控一个组件是否健康
- 编写一个类,继承AbstractHealthIndicator,并重写里面的抽象方法
//组件
@Component
public class MyComHealthIndicator extends AbstractHealthIndicator {
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
Map<String,Object> map = new HashMap<>();
// 检查完成
if(1 == 1){
//builder.up(); //健康
builder.status(Status.UP);
map.put("count",1);
map.put("ms",100);
}else {
//builder.down();
builder.status(Status.OUT_OF_SERVICE);
map.put("err","连接超时");
map.put("ms",3000);
}
builder.withDetail("code",100)
.withDetails(map);
}
}
management:
health:
enabled: true
show-details: always #总是显示详细信息。可显示每个模块的状态信息
- 还可以这样(了解即可):
@Component
public class MyHealthIndicator implements HealthIndicator {
@Override
public Health health() {
int errorCode = check(); // perform some specific health 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();
3.2、定制info信息
访问:http://localhost:8080/actuator/info
返回的信息
不定制的时候返回的是空
- 第一种方式:配置文件配置
info:
appName: boot-admin # 项目名字
version: 2.0.1
mavenProjectName: @project.artifactId@ #使用@@可以获取maven的pom文件值
mavenProjectVersion: @project.version@
- 第二种方式:编写配置类
InfoContributor
@Component
public class ExampleInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("example",
Collections.singletonMap("key", "value"));
}
}
3.3、定制Metrics信息
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
如何定制我们自己的监控指标:例如监控一个方法被调用了多少次
- 方式一:
//假设监控这个类的hello方法被调用的次数
public class MyService{
//计数相关的
Counter counter;
//有参构造器要这样写,形参为指标注册相关的类
public MyService(MeterRegistry meterRegistry){
//注册的名字
counter = meterRegistry.counter("myservice.method.running.counter");
}
public void hello() {
//加1操作
counter.increment();
}
}
- 方式二:直接在容器中注册一个
指标绑定
相关的类
@Bean
MeterBinder queueSize(Queue queue) {
return (registry) -> Gauge.builder("queueSize", queue::size).register(registry);
}
3.4、定制Endpoin
前面的都是在已有的端点进行拓展
如果官方给我们提供的监控端点不能满足我们的需求,我们就需要自定义监控端点
如何自定义监控端点:
@Component
//端点名字
@Endpoint(id = "myservice")
public class MyServiceEndPoint {
//端点读操作,即访问端点就会给我们返回的值
//http://localhost:8080/actuator/myservice
@ReadOperation
public Map getDockerInfo(){
return Collections.singletonMap("dockerInfo","docker started.....");
}
//端点的写操作,调用这个方法会在控制台打印一条信息
@WriteOperation
public void stopDocker(){
System.out.println("docker stopped.....");
}
}