Spring Boot Actuator - 如何向/ shutdown端点添加自定义逻辑

Mic*_*hal 6 java spring spring-boot spring-boot-actuator

在我的项目中,我开始使用Spring Boot Actuator.我使用/shutdown端点来优雅地停止嵌入式Tomcat(这很好用),但我还需要在关机期间做一些自定义逻辑.有什么办法,该怎么办?

Ali*_*ani 7

关闭应用程序之前,我可以想到两种方法来执行一些逻辑:

  1. 注册一个Filter,毕竟它是一个网络应用程序。
  2. invoke使用@Before通知拦截方法

小程序过滤器

由于/shutdown是一个 Servlet 端点,您可以在调用端点Filter之前注册一个运行/shutdown

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

也不要忘记注册它:

@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;
}
Run Code Online (Sandbox Code Playgroud)

定义一个 @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...");
    }
}
Run Code Online (Sandbox Code Playgroud)

也不要忘记启用AspectJAutoProxy

@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class Application { ... }
Run Code Online (Sandbox Code Playgroud)

spring-aspects依赖:

compile 'org.springframework:spring-aspects'
Run Code Online (Sandbox Code Playgroud)