如何在springboot执行项目停止操作(kill pid)之前,调用外部的restful接口,并且此时项目的各个类的生命周期都还没被杀死,求指点
3条回答 默认 最新
关注 可以在Spring Boot项目中使用Java的Runtime类来执行系统命令,从而调用外部的RESTful接口。具体步骤如下:
- 在Spring Boot项目中创建一个ShutdownHook类,该类实现了Java的Runnable接口,并在run方法中调用外部RESTful接口。
public class ShutdownHook implements Runnable { private String url; public ShutdownHook(String url) { this.url = url; } @Override public void run() { try { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); int responseCode = con.getResponseCode(); System.out.println("ShutdownHook executed, response code: " + responseCode); } catch (Exception e) { e.printStackTrace(); } } }
- 在Spring Boot项目的启动类中添加ShutdownHook,在项目停止时调用该类的run方法。
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication app = new SpringApplication(Application.class); app.addListeners(new ApplicationPidFileWriter()); app.addListeners(new ShutdownHook("http://localhost:8080/api/shutdown")); app.run(args); } }
- 在Spring Boot项目中添加一个RESTful接口,用于接收停止命令并执行停止操作。
@RestController @RequestMapping("/api") public class ShutdownController { @GetMapping("/shutdown") public void shutdown() { System.out.println("ShutdownController executed"); System.exit(0); } }
- 在命令行中执行kill命令,停止Spring Boot项目。
kill -15 <pid>
在执行kill命令时,Spring Boot项目会先执行ShutdownHook类的run方法,调用外部RESTful接口。然后再执行Spring Boot项目的停止操作,最后执行ShutdownController类的shutdown方法,完成项目的停止操作。
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥170 如图所示配置eNSP
- ¥20 docker里部署springboot项目,访问不到扬声器
- ¥15 netty整合springboot之后自动重连失效
- ¥15 悬赏!微信开发者工具报错,求帮改
- ¥20 wireshark抓不到vlan
- ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
- ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
- ¥15 stata安慰剂检验作图但是真实值不出现在图上
- ¥15 c程序不知道为什么得不到结果
- ¥15 键盘指令混乱情况下的启动盘系统重装