MST

星途 面试题库

面试题:Java中Spring Boot Actuator如何自定义端点

假设你正在使用Java的Spring Boot框架,并需要利用Actuator自定义一个端点来获取特定业务数据。请描述实现自定义端点的步骤,包括如何定义端点、如何暴露端点以及如何处理端点请求并返回数据。
27.2万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 定义端点
    • 创建一个类,实现Endpoint接口(在Spring Boot 2.x中,可实现Endpoint<MyResponse>MyResponse是自定义的返回数据类型)。例如:
    import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
    import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
    import org.springframework.stereotype.Component;
    
    @Endpoint(id = "custom - endpoint")
    @Component
    public class CustomEndpoint {
        @ReadOperation
        public String getCustomData() {
            // 这里编写获取特定业务数据的逻辑,返回业务数据
            return "specific business data";
        }
    }
    
    • @Endpoint注解用于标记该类为一个端点,id属性指定端点的唯一标识。
    • @ReadOperation注解标记的方法用于处理读取请求(如果是处理写入等其他操作,还有相应的@WriteOperation等注解)。
  2. 暴露端点
    • 在Spring Boot 2.x中,Actuator默认暴露的端点有限。要暴露自定义端点,需在application.propertiesapplication.yml中进行配置。
    • 如果使用HTTP,对于application.properties,可添加:
    management.endpoints.web.exposure.include = custom - endpoint
    
    • 对于application.yml
    management:
      endpoints:
        web:
          exposure:
            include: custom - endpoint
    
    • 这样配置后,自定义端点就可以通过HTTP被访问了。如果使用JMX等其他方式暴露端点,也有相应的配置方式,例如通过JMX暴露所有端点:
    management.endpoints.jmx.exposure.include = *
    
  3. 处理端点请求并返回数据
    • 在定义端点时,@ReadOperation等注解标记的方法内编写处理请求逻辑。
    • 如上述代码中getCustomData方法,在该方法内调用业务服务获取数据,例如调用数据库查询、调用其他微服务等,然后将获取到的数据返回。返回的数据类型需与方法定义的返回类型一致,Spring Boot会自动将返回的数据进行序列化(如JSON序列化,前提是添加了相应的依赖且配置正确),并返回给请求方。