[英]How to apply HandlerInterceptor to Spring Boot Actuator endpoints?
I'm working with Java 8 and Spring 1.2.3 to build an application running inside a Tomcat 7 container. 我正在使用Java 8和Spring 1.2.3来构建在Tomcat 7容器中运行的应用程序。
I do intercept every single call to my web application using a very simple HandlerInterceptor
, that logs the overall time taken to create a response and the return code for every request. 我确实使用非常简单的
HandlerInterceptor
拦截了对Web应用程序的每个调用,该操作记录了创建响应所花费的总时间以及每个请求的返回码。
I activated the actuator endpoints by simply adding the spring-boot-starter-actuator
dependency, and I add the interceptor by calling 我通过简单地添加
spring-boot-starter-actuator
依赖关系来激活执行器端点,然后通过调用添加拦截器
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
private Application application;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(application.executeTimeInterceptor());
}
}
Apparently, all endpoints managed by Spring Boot Actuator ( /info
, /health
and so forth) do not get intercepted: how can I make sure the interceptor intercepts all and every call made to my application, including the ones invoking an actuator-provided endpoint? 显然,Spring Boot Actuator管理的所有端点(
/info
, /health
等)都不会被拦截: 如何确保拦截器拦截对应用程序的所有调用,包括调用执行器提供的端点的调用?
In Spring Boot 1.x, you can use an EndpointHandlerMappingCustomizer
to configure the interceptors of the Actuator's endpoints. 在Spring Boot 1.x中,您可以使用
EndpointHandlerMappingCustomizer
配置执行器端点的拦截器。 For example: 例如:
@Bean
public EndpointHandlerMappingCustomizer mappingCustomizer() {
return new EndpointHandlerMappingCustomizer() {
@Override
public void customize(EndpointHandlerMapping mapping) {
mapping.setInterceptors(new Object[] { application.executeTimeInterceptor() });
}
};
}
In tomcat you can also add a valve to intercept calls to the web server. 在tomcat中,您还可以添加一个阀门来拦截对Web服务器的调用。 A valve will intercept all enpoints regardless of their interceptor stack.
阀门将拦截所有节点,而不管其拦截器堆栈如何。
Here is an example on how to implement a valve in spring boot: 以下是有关如何在弹簧套管中实施阀门的示例:
@Configuration
public class TomcatConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(TomcatConfiguration.class);
@Bean
public EmbeddedServletContainerFactory servletContainer() {
final TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addContextValves(new ValveBase() {
@Override
public void invoke(final Request request, final Response response) throws IOException, ServletException {
final long start = System.currentTimeMillis();
getNext().invoke(request, response);
LOG.debug("Used time to invoke " + request.getRequestURI() + " : " + (System.currentTimeMillis() - start));
}
});
return tomcat;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.