Spring Boot2.x如何自定义Endpoint

概述

在使用Spring Boot的时候我们经常使用actuator,健康检查,bus中使用/refresh等。这里记录如何使用注解的方式自定义Endpoint。可用于满足一些服务状态监控,或者优雅停机等。

准备

Spring Boot项目,pom中加入:


  org.springframework.boot
  spring-boot-starter-actuator

编写自定义Endpoint

@Configuration
@Endpoint(id = "my-endpoint")
public class MyEndpoint {
  @ReadOperation
  public Map endpoint() {
    Map map = new HashMap<>(16);
    map.put("message", "this is my endpoint");
    return map;
  }
}

1.配置

management.endpoints.web.exposure.include=my-endpoint

2.启动&测试

启动后可以看到日志:

Mapped "{[/actuator/my-endpoint],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)

3.注意

  • @EndPoint中的id不能使用驼峰法,需要以-分割。
  • @Spring Boot会去扫描@EndPoint注解下的@ReadOperation, @WriteOperation, @DeleteOperation注解,分别对应生成Get/Post/Delete的Mapping。注解中有个produces参数,可以指定media type, 如:application/json等。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(Spring Boot2.x如何自定义Endpoint)