本文基于spring boot 2.2.0 release版本。
在上一篇文章《spring boot Actuator原理详解之启动》详细介绍了在web环境下,Actuator是如何启动的,这里对流程做一个简单的总结:
明白了上面整个启动流程之后,我们也可以编写一个自定义的Endpoint。
自定义Endpoint的关键点:
Caused by: java.lang.IllegalStateException: No @Endpoint id attribute specified for XXXClass
;@ReadOperation、@WriteOperation、@DeleteOperation
;/actuator/caches/{cache}
花括号里面的内容是路径参数,我们可以在方法入参上添加@Selector来指定路径参数,比如public String counters(@Selector int value)
;@ReadOperation、@WriteOperation、@DeleteOperation
的produces属性指定其他格式。下面给出一个自定义Endpoint的例子:
/** * 统计方法该Endpoint对象的次数 */ @Component @Endpoint(id="counter") public class Counter { private AtomicInteger cnt=new AtomicInteger(0); @ReadOperation public int counter() { return cnt.getAndAdd(1); } @ReadOperation public int counters(@Selector int value) { return cnt.getAndAdd(value); } }
上面这个类只是一个示例,并没有实际意义。运行起来后,访问http://localhost:8079/actuator/counter
,每次访问都会返回一个比之前大1的数字。
我们还可以使用注解@EndpointWebExtension扩展已有的Endpoint。
下面是spring提供的对EnvironmentEndpoint的扩展:
@EndpointWebExtension(endpoint = EnvironmentEndpoint.class) public class EnvironmentEndpointWebExtension { private final EnvironmentEndpoint delegate; public EnvironmentEndpointWebExtension(EnvironmentEndpoint delegate) { this.delegate = delegate; } @ReadOperation public WebEndpointResponse<EnvironmentEntryDescriptor> environmentEntry(@Selector String toMatch) { EnvironmentEntryDescriptor descriptor = this.delegate.environmentEntry(toMatch); return new WebEndpointResponse<>(descriptor, getStatus(descriptor)); } private int getStatus(EnvironmentEntryDescriptor descriptor) { if (descriptor.getProperty() == null) { return WebEndpointResponse.STATUS_NOT_FOUND; } return WebEndpointResponse.STATUS_OK; } }
就web环境下来说,如果扩展类的方法有与原类相同的http请求路径,那么扩展类会替换掉原来的方法,也就是说,访问该路径时,不会访问到原类的方法,而是访问到扩展类。
上一个:领养宠物百科(领养宠物须知)