且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

spring-boot actuator(监控)配置和使用

更新时间:2022-06-20 09:19:55

spring-boot actuator(监控)配置和使用

spring-boot actuator(监控)配置和使用

在生产环境中,需要实时或定期监控服务的可用性。spring-boot 的actuator(监控)功能提供了很多监控所需的接口。简单的配置和使用如下:

1、引入依赖:

[html] view plain copy

  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-actuator</artifactId>
  4. </dependency>

如果使用http调用的方式,还需要这个依赖:

[html] view plain copy

  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>

2、配置:

application.yml中指定监控的HTTP端口(如果不指定,则使用和server相同的端口);指定去掉某项的检查(比如不监控health.mail):

[plain] view plain copy

  1. server:
  2.   port: 8082
  3. management:
  4.   port: 54001
  5.   health:
  6.     mail:
  7.       enabled: false

 

3、使用:

查看health指标:http://localhost:54001/health

[plain] view plain copy

  1. {"status":"UP","diskSpace":{"status":"UP","total":120031539200,"free":33554337792,"threshold":10485760},"db":{"status":"UP","dataSource1":{"status":"UP","database":"MySQL","hello":1},"dataSource2":{"status":"UP","database":"MySQL","hello":1}}}

4、自定义指标:
4.1 /health:在某个类中implements HealthIndicator接口,然后实现其中的health()方法即可:

代码:

[java] view plain copy

  1. @SpringBootApplication
  2. @EnableScheduling
  3. public class MySpringBootApplication implements HealthIndicator{
  4.     private static Logger logger = LoggerFactory.getLogger(MySpringBootApplication.class);
  5.     public static void main(String[] args) {
  6.         SpringApplication.run(MySpringBootApplication.class, args);
  7.         logger.info("My Spring Boot Application Started");
  8.     }
  9.     /**
  10.      * 在/health接口调用的时候,返回多一个属性:"mySpringBootApplication":{"status":"UP","hello":"world"}
  11.      */
  12.     @Override
  13.     public Health health() {
  14.         return Health.up().withDetail("hello""world").build();
  15.     }
  16. }

/health 运行结果(注意第二个指标):

{"status":"UP","mySpringBootApplication":{"status":"UP","hello":"world"},"diskSpace":{"status":"UP","total":120031539200,"free":33554337792,"threshold":10485760},"db":{"status":"UP","dataSource1":{"status":"UP","database":"MySQL","hello":1},"dataSource2":{"status":"UP","database":"MySQL","hello":1}}}

4.2 /info:配置如下,可以直接给一个字符串,也可以从pom.xml配置中获取

[plain] view plain copy

  1. info:
  2.   app:
  3.     name: "@project.name@" #从pom.xml中获取
  4.     description: "@project.description@"
  5.     version: "@project.version@"
  6.     spring-boot-version: "@project.parent.version@"

/info的结果如下:

{"app":{"name":"my-spring-boot","description":"Test Project for Spring Boot","version":"1.0","spring-boot-version":"1.3.6.RELEASE"}}

原文地址http://www.bieryun.com/1776.html