首页 > 编程语言 >如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?

时间:2023-04-07 17:34:19浏览次数:45  
标签:info http java Spring Boot 应用程序 health 端点 actuator

1 概述

1.1 整合

添加依赖:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-actuator</artifactId>
 </dependency>

启动应用,会观察到如下日志:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_java

13:15:17.642 ifp [main] INFO  o.s.b.a.e.web.EndpointLinksResolver - Exposing 2 endpoint(s) beneath base path '/actuator'
 13:15:17.654 ifp [main] INFO  o.s.b.a.e.w.s.WebMvcEndpointHandlerMapping - Mapped "{[/actuator/health],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
 13:15:17.655 ifp [main] INFO  o.s.b.a.e.w.s.WebMvcEndpointHandlerMapping - Mapped "{[/actuator/info],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
 13:15:17.656 ifp [main] INFO  o.s.b.a.e.w.s.WebMvcEndpointHandlerMapping - Mapped "{[/actuator],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto protected java.util.Map<java.lang.String, java.util.Map<java.lang.String, org.springframework.boot.actuate.endpoint.web.Link>> org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping.links(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
 

打开链接,得到结果:

{
     "_links": {
         "self": {
             "href": "http://localhost:19086/actuator",
             "templated": false
         },
         "health": {
             "href": "http://localhost:19086/actuator/health",
             "templated": false
         },
         "info": {
             "href": "http://localhost:19086/actuator/info",
             "templated": false
         }
     }
 }

点击此处:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_java_02

可见:

http://localhost:19086/actuator/health:
 
 {
   "status": "UP"
 }

1.2 暴露端点

默认打开的只有 health 和 info 端点,其实还支持很多端点:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_git_03

要展示其他端点,需配置:

SpringBoot支持很多端点,除了默认显示的几个,还可激活暴露所有端点:

management:
   endpoints:
     web:
       exposure:
         include: '*'

观察日志:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_java_04

若仅想暴露某端点也可:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_spring_05

具体维度的指标,还得细化,如查看JVM最大内存:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_java_06

2 健康信息

健康信息可以检查应用的运行状态,它经常被监控软件用来提醒人们生产环境是否存在问题。health端点暴露的默认信息取决于端点是如何被访问的。

  • 对于一个非安全,未认证的连接只返回一个简单的'status'信息
  • 对一个安全或认证过的连接其他详细信息也会展示

2.1 顶层接口

package org.springframework.boot.actuate.health;
 
 /**
  * 这个接口可以通过某种策略来判断程序应用的健康状况
  *
  * @author Dave Syer
  * @see ApplicationHealthIndicator
  */
 @FunctionalInterface
 public interface HealthIndicator {
 
   /**
    * 返回健康状况的指示
    * 这个指示可以告诉程序用户或管理员系统的健康程度,以供后续决策和操作。
    */
   Health health();
 
 }
 

Health的数据结构如下:

@JsonInclude(Include.NON_EMPTY)
 public final class Health {
 
   private final Status status;
 
   private final Map<String, Object> details;
   ...
 }

Spring Boot 内置了很多自动配置的HealthIndicator,当然也能自定义:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_spring_07

2.2 自动配置的HealthIndicators

Spring Boot在合适时候,会自动配置如下HealthIndicator:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_spring_08

内置状态的默认状态映射:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_java_09

  • UP:正常
  • DOWN:遇到了问题,不正常
  • OUT OF SERVICE:资源未在使用或不该使用
  • UNKNOWN:未知

配置下health节点,并重启:

management:
   endpoint:
     health:
       show-details: always

可看到对磁盘的监控信息:

http://localhost:19086/actuator/health

{
    "status": "UP",
    "details": {
        "diskSpace": {
            "status": "UP",
            "details": {
                "total": 499963174912,
                "free": 22110871552,
                "threshold": 10485760
            }
        },
        "db": {
            "status": "UP",
            "details": {
                "database": "MySQL",
                "hello": 1
            }
        }
    }
}

2.3 执行流程

DataSourceHealthIndicator 为例,在这打断点:

@Override
	protected void doHealthCheck(Health.Builder builder) throws Exception {
		if (this.dataSource == null) {
			builder.up().withDetail("database", "unknown");
		}
		else {
			doDataSourceHealthCheck(builder);
		}
	}

刷新 http://localhost:19086/actuator/health,进入断点:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_spring_10

private void doDataSourceHealthCheck(Health.Builder builder) throws Exception {
  // ①
  String product = getProduct();
  // 就开始拼接要输出的信息了
  builder.up().withDetail("database", product);
  // ②
  String validationQuery = getValidationQuery(product);
  if (StringUtils.hasText(validationQuery)) {
    // Avoid calling getObject as it breaks MySQL on Java 7
    List<Object> results = this.jdbcTemplate.query(validationQuery,
        new SingleColumnRowMapper());
    // ③
    Object result = DataAccessUtils.requiredSingleResult(results);
    builder.withDetail("hello", result);
  }
}

①其实就是进入数据库驱动包,获取到具体的数据库名称:

String product = getProduct();

private String getProduct() {
  return this.jdbcTemplate.execute((ConnectionCallback<String>) this::getProduct);
}

private String getProduct(Connection connection) throws SQLException {
  return connection.getMetaData().getDatabaseProductName();
}

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_git_11

②得到:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_git_12

③得到hello 拼接的结果:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_java_13

一旦doHealthCheck方法抛异常,就会被catch:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_git_14

3 应用信息

点击此处,就能进入 info 端点:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_java_15

应用信息会暴露所有InfoContributor beans收集的各种信息,Spring Boot内置很多自动配置的InfoContributors,也可自定义。

3.1 自动配置的InfoContributor

Spring Boot会在合适的时候自动配置如下InfoContributor:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_spring_16

注 使用management.info.defaults.enabled属性可禁用以上所有InfoContributor。

3.2 自定义应用info信息

通过设置Spring属性info.*,你可以定义info端点暴露的数据。所有在info关键字下的Environment属性都将被自动暴露,例如,你可以将以下配置添加到application.properties:

info:
  project-name: car-receiver
  author: JavaEdge
  app:
    encoding: UTF-8
    java:
      source: 1.8
      target: 1.8

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_spring_17

这种信息有啥实际用途呢?比如在接收到告警后的业务处理,我们就能根据服务发现组件上面的服务名称,找到对应的/actuator/info,进而找到对应的owner-email配置的值,发给对应微服务的负责人即可。

可在构建时扩展info属性,而非硬编码这些值。假设使用Maven,可按如下配置重写示例:

[email protected]@
[email protected]@
[email protected]@

3.3 Git提交信息

info端点的另一有用特性,在项目构建完成后发布git源码仓库的状态信息。若GitProperties bean可用,Spring Boot将暴露git.branch,git.commit.id和git.commit.time属性。

若classpath根目录存在git.properties文件,Spring Boot将自动配置GitProperties bean。

使用management.info.git.mode可展示全部git信息(如git.properties的全部内容):

management.info.git.mode=full

3.4 构建信息

若BuildProperties bean存在,info端点也会发布你的构建信息。

若classpath下存在META-INF/build-info.properties文件,Spring Boot将自动构建BuildProperties bean。Maven和Gradle都能产生该文件

配置info:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_git_18

启动观察输出信息:

如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_spring_19

4 Beans

Bean 端点提供有关应用程序 bean 的信息。

获取 Beans

  • /actuator/beans GET 请求
  • 如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_git_20

  • 响应的结构:
  • 如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_spring_21

  • 结果中可见 SpringBoot 默认的数据源:
  • 如何在 Spring Boot 应用程序中使用 Actuator 监控和管理端点,提高应用程序的生产力?_java_22

5 总结

的确很方便,可是 JSON 形式的,如何更加可视化呢?敬请期待

标签:info,http,java,Spring,Boot,应用程序,health,端点,actuator
From: https://blog.51cto.com/u_11440114/6174191

相关文章

  • 实战-JAVA应用程序CPU占用率飙升,定位线程的堆栈信息
    分以下几个步奏:(1)使用命令top-p<pid>,显示你的java进程的cpu情况,pid是你的java进程号,比如14203。(使用jps可以获取到java的进程id或者top直接查看)(2)按H,获取每个线程的CPU情况。(shirt+H)(3)找到内存和cpu占用最高的线程tid,比如14204。(4)转为十六进制得到377C,此为线程id的十六进......
  • SpringBoot2核心技术篇(自动配置原理入门[二])
    自动配置原理入门3.1引导加载自动配置类@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan(excludeFilters={@Filter(type=FilterType.CUSTOM,classes={TypeExcludeFilter.class}),@Filter(type=FilterType.CUSTOM,classes=......
  • 动力节点王鹤SpringBoot3笔记——第四章 访问数据库
    视频:动力节点SpringBoot3从入门到项目实战第四章访问数据库SpringBoot框架为SQL数据库提供了广泛的支持,既有用JdbcTemplate直接访问JDBC,同时支持“objectrelationalmapping”技术(如Hibernate,MyBatis)。SpringData独立的项目提供对多种关系型和非关系型数据库的访问支持。......
  • 动力节点王鹤SpringBoot3笔记—— 第二章 掌控SpringBoot基础篇
    第二章掌控SpringBoot基础篇2.1SpringBoot?SpringBoot是目前流行的微服务框架倡导约定优先于配置”其设目的是用来简化新Spring应用的初始化搭建以及开发过程。SpringBoot提供了很多核心的功能,比如自动化配置starter(启动器)简化Maven配置、内嵌Servlet容......
  • 动力节点王鹤SpringBoot3笔记——第五章 说说Web服务
    第五章说说Web服务基于浏览器的B/S结构应用十分流行。SpringBoot非常适合Web应用开发。可以使用嵌入式Tomcat、Jetty、Undertow或Netty创建一个自包含的HTTP服务器。一个SpringBoot的Web应用能够自己独立运行,不依赖需要安装的Tomcat,Jetty等。SpringBoot可以创建两种类型的Web应......
  • 动力节点王鹤SpringBoot3学习笔记——第五章 说说Web服务
    第五章说说Web服务基于浏览器的B/S结构应用十分流行。SpringBoot非常适合Web应用开发。可以使用嵌入式Tomcat、Jetty、Undertow或Netty创建一个自包含的HTTP服务器。一个SpringBoot的Web应用能够自己独立运行,不依赖需要安装的Tomcat,Jetty等。SpringBoot可以创建两种类型的Web应......
  • 动力节点王鹤SpringBoot3学习笔记——第五章 说说Web服务
    第五章说说Web服务基于浏览器的B/S结构应用十分流行。SpringBoot非常适合Web应用开发。可以使用嵌入式Tomcat、Jetty、Undertow或Netty创建一个自包含的HTTP服务器。一个SpringBoot的Web应用能够自己独立运行,不依赖需要安装的Tomcat,Jetty等。SpringBoot可以创建两种类型的Web应......
  • Spring Boot中的MVC支持
    1.1概述SpringBoot的MVC支持主要来介绍实际项目中最常用的几个注解,包括@RestController、@RequestMapping、@PathVariable、@RequestParam以及@RequestBody。主要介绍这几个注解常用的使用方式和特点。1.2@RestController@RestController是SpringBoot新增的一个注解,我们......
  • Spring Boot中使用拦截器
    1.1概述拦截器的原理很简单,是AOP的一种实现,专门拦截对动态资源的后台请求,即拦截对控制层的请求。使用场景比较多的是判断用户是否有权限请求后台,更拔高一层的使用场景也有,比如拦截器可以结合websocket一起使用,用来拦截websocket请求,然后做相应的处理等等。拦截器不会拦截静态资......
  • [ Spring事件发布与监听 ]
    Spring事件监听与发布主要有以下部分:事件(被监听的玩意),事件发布(把这个事件发布出去),事件监听(用来监听事件,并做行动)项目中,因为事件类型不同,可以先定义事件的接口:Ievent:publicinterfaceIEvent{}对于具体的事件,可以实现IEvent接口:(ep:后端需要判断一个对象中是否......