I'm working with Java 8 and Spring 1.2.3 to build an application running inside a Tomcat 7 container.
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.
I activated the actuator endpoints by simply adding the spring-boot-starter-actuator
dependency, and I add the interceptor by calling
@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?
In Spring Boot 1.x, you can use an EndpointHandlerMappingCustomizer
to configure the interceptors of the Actuator's endpoints. 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. 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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.