在项目上线后,或者未来每一个微服务在云上部署以后,我们都需要对其进行监控、追踪、审计、控制等。SpringBoot就抽取了Actuator场景,使得我们每个微服务快速引用即可获得生产级别的应用监控、审计等功能。
依赖坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
SpringBoot Actuator 1.x与2.x的不同
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
最常用的Endpoint * Health:监控状况 * Metrics:运行时指标 * Loggers:日志记录
健康检查端点,我们一般用于在云平台,平台会定时的检查应用的健康状况,我们就需要Health Endpoint可以为平台返回当前应用的一系列组件健康状况的集合。
访问信息路径:http://localhost:8080/actuator/health
重要的几点: * health endpoint返回的结果,应该是一系列健康检查后的一个汇总报告 * 很多的健康检查默认已经自动配置好了,比如:数据库、redis等 * 可以很容易的添加自定义的健康检查机制
提供详细的、层级的、空间指标信息,这些信息可以被pull(主动推送)或者push(被动获取)方式得到; * 通过Metrics对接多种监控系统 * 简化核心Metrics开发 * 添加自定义Metrics或者扩展已有Metrics
访问信息路径:http://localhost:8080/actuator/metrics
* 默认所有的Endpoint除了shutdown都是开启的。 * 需要开启或者禁用某个Endpoint。配置模式为 management.endpoint.<endpointName>.enabled = true
management:
endpoint:
beans:
enabled: true
management:
endpoints:
enabled-by-default: false
endpoint:
beans:
enabled: true
health:
enabled: true
* HTTP:默认只暴露health和info Endpoint * JMX:默认暴露所有Endpoint * 除了health和info,剩下的Endpoint都应该进行保护访问。如果引入SpringSecurity,则会默认配置安全访问
开启Endpoints和暴露Endpoints可以做以下配置
## management 是所有actuator的配置
## management.endpoint.端点名.xxxx 对某个端点的具体配置
management:
endpoints:
#默认开启所有监控端点
enabled-by-default: true
web:
exposure:
## 以web方式暴露所有端点
include: '*'
endpoint: #对某个端点的具体配置
health:
show-details: always
enabled: true
info:
enabled: true
beans:
enabled: true
metrics:
enabled: true
在开发中,如果需要自己定义指标端点用于监控某一项功能或者模块,我们就可以使用自己定制 Endpoint端点,来达到自定义数据统计和指标监控的效果。 尝试定制四类端点信息 1. 定制 Health 信息 2. 定制info信息 3. 定制Metrics信息 4. 定制Endpoint
目录结构如下
management:
health:
enabled: true
show-details: always #总是显示详细信息。可显示每个模块的状态信息
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Status;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* @author tao
* @date 2021-08-25 23:09
* 概要:自定义健康组件
*/
//将组件放在容器中,其中 myCom 是该健康组件的名字
@Component
public class MyComHealthIndicator extends AbstractHealthIndicator {
/**
* 真实的检查方法
*
* @param builder
* @throws Exception
*/
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
//mongodb 获取连接进行测试
Map<String, Object> map = new HashMap<>();
//检查完成
if (1 == 1) {
//健康
//builder.up();
builder.status(Status.UP);
map.put("count", 1);
map.put("ms", 200);
} else {
//宕机
builder.down();
builder.status(Status.OUT_OF_SERVICE);
map.put("err", "连接超时");
map.put("ms", 5000);
}
builder.withDetail("code", 100).withDetails(map);
}
}
常用两种方式 1、编写配置文件
#定制监控的info信息
info:
appName: @project.name@
version: 2.0.1
#使用@@可以获取maven的pom文件值,需要在pom文件里面添加配置信息
mavenProjectName: @project.artifactId@
mavenProjectVersion: @project.version@
注意: 使用@@可以获取maven的pom文件值,需要在pom文件里面添加配置信息 但是如果使用@@表达式报错或者没有提示时,可能时因为pom.mxl中没有打开@@获取pom文件信息 需要如下操作: * 在<build>标签下加入以下配置
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<!--允许使用@@获取pom文件信息-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<delimiters>
<delimiter>@</delimiter>
</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
</configuration>
</plugin>
启用配置后就OK了。 2. 编写InfoContributor.java配置类
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* @author tao
* @date 2021-08-25 23:42
* 概要:
*/
@Component
public class AppInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("msg", "你好");
builder.withDetail("hello", "如我西沉");
Map<String, Object> map = new HashMap<>();
map.put("phoneNum", "1205529635");
map.put("QQ", "1205529635");
map.put("name", "Nick");
builder.withDetails(map);
}
}
* 计数器(Counter): 表示收集的数据是按照某个趋势(增加/减少)一直变化的,也是最常用的一种计量器,例如接口请求总数、请求错误总数、队列数量变化等。 * 计量仪(Gauge): 表示搜集的瞬时的数据,可以任意变化的,例如常用的 CPU Load、Mem 使用量、Network 使用量、实时在线人数统计等, * 计时器(Timer): 用来记录事件的持续时间,这个用的比较少。 * 分布概要(Distribution summary): 用来记录事件的分布情况,表示一段时间范围内对数据进行采样,可以用于统计网络请求平均延迟、请求延迟占比等。
在SpringBoot集成的Actuator中,MeterRegistry提供的方法如下
2. 增加定制Metrics 场景: 在自己编写了一个查询所有用户的接口后,想统计这个接口被调用的次数,因此在Actuator增加一个定制的Metrics指标,来监控接口的使用情况。 步骤: * 定义一个计量器(Counter) * 在构造方法中传入MeterRegistry * 使用meterRegistry构造一个计量器(counter) * 使用计量器进行增加数据:counter.increment();
因此可以在Service层编写定制Metrics的逻辑。 实现代码如下:
/**
* @author tao
* @date 2021-08-16 22:33
* 概要:
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
private UserMapper userMapper;
private Counter counter;
//在构造方法中传入MeterRegistry
public UserServiceImpl(MeterRegistry meterRegistry) {
counter = meterRegistry.counter("UserService.findAll.count");
}
@Override
public List<User> findAll() {
//增加数据
counter.increment();
return userMapper.selectList(null);
}
}
* 访问路径:http://localhost:8080/actuator/metrics 会发现多了一个指标
这个是定制的metrics * 可以访问:http://localhost:8080/actuator/metrics/UserService.findAll.count 拿到计量监控数据
* 调用几次接口后
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.Map;
/**
* @author tao
* @date 2021-08-26 0:45
* 概要:自定义监控端点
*/
@Component
@Endpoint(id = "myService")
public class MyServiceEndpoint {
@ReadOperation
public Map getDockerInfo() {
return Collections.singletonMap("info", "docker started...");
}
@WriteOperation
private void stopDocker() {
System.out.println("docker stop....");
}
}
注意:@Spring Boot会去扫描@EndPoint注解下的@ReadOperation, @WriteOperation, @DeleteOperation注解,分别对应生成Get/Post/Delete的Mapping。注解中有个produces参数,可以指定media type, 如:application/json等。 3. 测试效果 配置好自定义EndPoint后,查看:http://localhost:8080/actuator 会发现已经出现有自己配置的EndPoint端点
SpringBoot提供了一个开源的SpringBoot Actuator指标监控可视化项目,可以点击下面链接进行下载学习,也可以拿到我文章末尾的代码源码。 https://github.com/codecentric/spring-boot-admin
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
## 应用名称
spring.application.name=springboot-adminserver
## 应用服务 WEB 访问端口
server.port=8888
@SpringBootApplication
@EnableAdminServer
public class SpringbootAdminserverApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAdminserverApplication.class, args);
}
}
spring:
boot:
admin:
client:
url: http://localhost:8888
instance:
prefer-ip: true #使用IP将可视化项目注册进来
链接:https://pan.baidu.com/s/1ZWzb3dNo-YnInyBdjTXRqw 提取码:50ap
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有