[英]Spring Boot Actuator - how to add custom logic to /shutdown endpoint
在我的项目中,我开始使用Spring Boot Actuator。 我使用/shutdown
端点来优雅地停止嵌入式Tomcat(这很好用),但我还需要在关机期间做一些自定义逻辑。 有什么办法,该怎么办?
我可以想到在关闭应用程序之前执行某些逻辑的两种方法:
Filter
,毕竟它是一个Web应用程序。 @Before
建议拦截invoke
方法 由于/shutdown
是一个Servlet端点,您可以在调用/shutdown
端点之前注册一个Filter
来运行:
public class ShutdownFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
// Put your logic here
filterChain.doFilter(request, response);
}
}
另外不要忘记注册它:
@Bean
@ConditionalOnProperty(value = "endpoints.shutdown.enabled", havingValue = "true")
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new ShutdownFilter());
registrationBean.setUrlPatterns(Collections.singleton("/shutdown"));
return registrationBean;
}
@Aspect
如果向/shutdown
端点发送请求,假设启用了关闭端点且安全性未阻止请求,则将invoke
方法。 您可以定义@Aspect
来拦截此方法调用并将您的逻辑放在那里:
@Aspect
@Component
public class ShutdownAspect {
@Before("execution(* org.springframework.boot.actuate.endpoint.ShutdownEndpoint.invoke())")
public void runBeforeShutdownHook() {
// Put your logic here
System.out.println("Going to shutdown...");
}
}
另外不要忘记启用AspectJAutoProxy
:
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class Application { ... }
和spring-aspects
依赖:
compile 'org.springframework:spring-aspects'
调用它时,关闭端点会调用应用程序上下文中的close()
。 这意味着可以使用在关闭处理期间运行某些自定义逻辑的所有常用机制。
例如,你可以一个bean添加到实现应用程序上下文DisposableBean
或者使用destroyMethod
的属性@Bean
在声明通过Java配置一个bean:
@Bean(destroyMethod="whateverYouWant")
public void Foo {
return new Foo();
}
如果您创建自定义ShutdownEndpoint bean,则可以添加自定义逻辑。
@Component
public class CustomShutdownEndpoint extends ShutdownEndpoint {
@Override
public Map<String, Object> invoke() {
// Add your custom logic here
return super.invoke();
}
}
通过这种方式,您可以更改任何逻辑弹簧 - 启动 - 执行器端点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.