在基于Spring Boot的应用程序内通过Endpoint可以根据应用程序业务需求实现自定义的监控接口,但目前的版本中实现自定义Endpoint需要实现该接口内的以下几个方法, 代码稍显复杂:
String getId();
boolean isEnabled();
boolean isSensitive();
T invoke();
而经过重新设计后的Spring Boot 2 在Endpoint方面带来了全新的架构,实现自定义Endpoint的代码相当精简,可读性更强,例如以下代码实现了URI路径为/customPoint的一个监控点, 此特性会在2.0.0.M4以及当前的2.0.0.BUILD-SNAPSHOT中得到支持。
@Endpoint(id = "customPoint")
public class CustomEndPoint {
@ReadOperation
public String getCustom(@Selector String name) {
return "MyName is ." + name;
}
}
经过测试,目前2.0.0.BUILD-SNAPSHOT版本的Endpoint也可以在Kotlin代码中以更精简的形式实现,以下的代码实现了/ktpoint/{name} 的只读接口函数和可写控制接口, 不过目前在可写类监控点中通过POST方式提交JSON格式的参数一直无法正常传送到Endpoint的WriteOperation方法中,暂未查明具体原因。
URI (HTTP.Method) | 注解 | 说明 |
---|---|---|
/ktpoint/{name} (GET) | @ReadOperation | 只读类监控点 |
/ktpoint/{name} (POST) | @WriteOperation | 可写类监控点 |
@Endpoint(id = "ktpoint")
class MyKtPoint(var pointName: String) {
@ReadOperation
fun getIt(@Selector name: String) = hello("MyName is .${name} ${pointName}")
@WriteOperation
fun changePointName(@Selector name: String): KtPoint {
this.pointName = name
return KtPoint(this.pointName)
}
}
为保证以上的Endpoint能顺利通过响应的URL访问,需要以Spring Bean的方式注册到系统的上下文环境中,以下两种方式都可以确保Endpoint顺利注册:
注解 | 注解所在位置 | 代码示例 |
---|---|---|
@Component | 自定义Endpoint类 | @Endpoint(id = "customPoint") @Component public class CustomEndPoint { @ReadOperation public String getCustom(@Selector String name) { return "MyName is ." + name; } } |
@Bean | @Configuration类 | @Bean public CustomEndPoint getEndpoint() { return new CustomEndPoint(); } |
以上示例的源码文件可在码云仓库下载,链接地址: act-demo2,
参考资料:
https://spring.io/blog/2017/08/22/introducing-actuator-endpoints-in-spring-boot-2-0
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有