SpringBoot2.x系列教程56--SpringBoot实现状态监测及项目关闭功能
前言
壹哥 在之前就跟大家说过,SpringBoot是一个很“牛逼”的开发技术,它不仅极大的简化了我们的Web开发,而且还可以与其他很多已有的Java技术无缝对接。今天 壹哥 会跟各位介绍在SpringBoot中整合监控功能,从而让我们时刻了解项目的运行状态及各种内部信息。
一. SpringBoot监控功能
1. 监控功能简介
在之前的系列文章中我们学习了如何进行Spring Boot应用的功能开发,以及如何写单元测试、集成测试等,然而,在实际的软件开发中需要做的不仅如此:还包括对应用程序的监控和管理。
我们也需要实时看到自己的应用目前的运行情况,比如给定一个具体的时间,我们希望知道此时CPU的利用率、内存的利用率、数据库连接是否正常以及在给定时间段内有多少客户请求等指标。不仅如此,我们还希望通过图表、控制面板来展示上述信息。
我们可以通过HTTP,JMX,SSH协议来进行操作,自动得到审计、健康及指标信息等。
2. 实现步骤
- 引入spring-boot-starter-actuator;
- 通过http方式访问监控端点;
- 可进行shutdown(POST 提交,此端点默认关闭)。
3. 监控和管理端点
4. 定制端点信息
- 开启远程应用关闭功能: management.endpoint.shutdown.enabled=true
- 开启所需端点: management.endpoint.beans.enabled=true
- 定制端点访问根路径: management.endpoints.web.base-path=/manage
二. 具体实现步骤
1. 创建web项目
我们按照之前的经验,创建一个Web程序,并将之改造成Spring Boot项目,具体过程略。
2. 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
3. 添加配置信息
package com.yyg.boot.config;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
/**
* @Author 一一哥Sun
* @Date Created in 2020/5/15
* @Description Description
*/
@Component
public class MyHealthIndicator implements HealthIndicator {
@Override
public Health getHealth(boolean includeDetails) {
return null;
}
@Override
public Health health() {
//自定义的检查方式
Health.up().build(); //代表健康,服务没问题。
//服务GG了
Health.down().withDetail("message", "服务异常").build();
return null;
}
}
4. 创建入口类
package com.yyg.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Author 一一哥Sun
* @Date Created in 2020/5/15
* @Description Description
*/
@SpringBootApplication
public class ActuatorApplication {
public static void main(String[] args){
SpringApplication.run(ActuatorApplication.class,args);
}
}
5.创建application.yml配置文件
management:
#security:
#enabled: false
endpoint:
beans:
enabled: true
health:
show-details: always
enabled: true
shutdown:
enabled: true #开启关闭功能,默认关闭
endpoints:
web:
base-path: "/actuator" #默认的访问路径
exposure:
#include: ["health","info"]
include: "*"
#exclude: "env,beans"
三. 进行测试
1. 查看项目的健康状态 
2. 查看项目中的beans信息 
3. 查看项目的所有配置信息 
4. 测试关闭项目功能
在postman中通过post请求方式,测试关闭项目功能。
结语
至此,壹哥 通过一些简单的配置,就把监控功能轻松的整合到了SpringBoot项目中了,以后你再也不用担心会发生自己的项目挂了都不知道的情况了。
转载自:https://juejin.cn/post/7178995303251443767