Spring Boot Actuator自定义Endpoint
Endpoint注解简介
自定义Endpoint有两种方式,一种是实现指定的接口,但已经废弃了。另外一种就是基于注解的形式来实现。
常见的注解有:@Endpoint、@WebEndpoint、@ControllerEndpoint、@RestControllerEndpoint、@ServletEndpoint。
Endpoint的使用比较简单,首先在类上使用@Endpoint注解,然后对应类的方法上使用@ReadOperation或@WriteOperation或@DeleteOperation,此时该方法将通过JMX自动公开,并且在Web应用程序中也可以通过Http方式进行访问。
通常,只有在项目中使用了Jersey,Spring MVC或Spring WebFlux组件时才会使用HTTP协议来公开端点。
上述三个注解分别对应三个Http请求的Method,依次对照为:GET、POST、DELETE。
Endpoint示例
下面来看一个简单的示例:
@Endpoint(id = "hello")
@Component
public class SimpleEndpoint {
@ReadOperation
public String getHello(){
return "get Hello";
}
@WriteOperation
public String postHello(){
return "post Hello";
}
@DeleteOperation
public String deleteHello(){
return "delete Hello";
}
}
通过上述方式就公开了一个Endpoint,对应的URL为/actuator/hello,其中/actuator为自定义的根路径,而对应的方法请求,根据Http Method进行对照即可。
Endpoint扩展
Endpoint传递参数仅支持简单对象,不支持复杂对象。
使用@Seleter可以增加路径参数:
@ReadOperation
public String getHelloWithName(@Selector String name){
return "get Hello";
}
使用后对应路径为:
"hello-name": {
"href": "http://127.0.0.1:8080/actuator/hello/{name}",
"templated": true
}
也可能生成以下路径:
"hello-args0": {
"href": "http://127.0.0.1:8080/actuator/hello/{args0}",
"templated": true
}
在java 1.8以下几某些1.8低版本中编译出来的class是无法取到参数名的,会导致该接口使用失败,需要在编译时添加-parameters参数然后进行编译。

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台
除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接
本文链接:https://choupangxia.com/2021/07/07/spring-boot-actuator-endpoint/