springboot优雅停机

springboot想要在项目关闭前执行一系列操作, 直接实现implements ApplicationListener<ContextClosedEvent>以debug方式启动,打断点到方法上,日志打印了,但是断点没有断住,只有调用“优雅停机”接口curl localhost:8080/actuator/shutdown才会进入断点,其中缘由不太清楚,知道的大佬烦请告知,断点没有进入方法,但是方法里面的业务都执行了

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
  • yml配置
management:
  endpoint:
    shutdown:
      enabled: true
  endpoints:
    web:
      exposure:
        include:
          - shutdown
  • 测试方法
package org.example.springboottest.lisenter;

import lombok.extern.slf4j.Slf4j;
import org.example.springboottest.service.TestService;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

@Slf4j
@Configuration
public class Test implements ApplicationListener<ContextClosedEvent> {

    @Resource
    private TestService testService;

    /**
     * 方式1 通过ApplicationListener 监听ContextClosedEvent事件
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        log.info("关闭context..........");
        testService.test();
    }

    /**
     * 方式2 通过@PreDestroy 注解生命销毁前调用此方法
     */
    @PreDestroy
    public void onDestroy() {
        System.out.println("PreDestroy called...");
    }
}

  • 测试
curl localhost:8080/actuator/shutdown

1 个赞

有可能是jvm或者springboot处理两种stop信号的方式不同

这是正常的,你在IDEA中点停止按钮,debug断点即不再生效。
调用 shutdown接口不是在IDEA中操作,因此断点生效。