如何优雅的停止SpringBoot服务?
java1234
共 4723字,需浏览 10分钟
·
2020-10-29 23:58
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
org.springframework.boot
spring-boot-starter-actuator
server.port=3333
management.endpoint.shutdown.enabled=true
management.endpoints.web.exposure.include=shutdown
package com.hqs.springboot.shutdowndemo.bean;
import javax.annotation.PreDestroy;
publicclassTerminateBean{
@PreDestroy
publicvoid preDestroy() {
System.out.println("TerminalBean is destroyed");
}
}
package com.hqs.springboot.shutdowndemo.config;
import com.hqs.springboot.shutdowndemo.bean.TerminateBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
publicclassShutDownConfig{
@Bean
publicTerminateBean getTerminateBean() {
returnnewTerminateBean();
}
}
curl -X POST http://localhost:3333/actuator/shutdown
/* method 2: use ctx.close to shutdown all application context */
ConfigurableApplicationContext ctx = SpringApplication.run(ShutdowndemoApplication.class, args);
try{
TimeUnit.SECONDS.sleep(10);
} catch(InterruptedException e) {
e.printStackTrace();
}
ctx.close();
/* method 3 : generate a pid in a specified path, while use command to shutdown pid :
'cat /Users/huangqingshi/app.pid | xargs kill' */
SpringApplication application = newSpringApplication(ShutdowndemoApplication.class);
application.addListeners(newApplicationPidFileWriter("/Users/huangqingshi/app.pid"));
application.run();
/* method 4: exit this application using static method */
ConfigurableApplicationContext ctx = SpringApplication.run(ShutdowndemoApplication.class, args);
exitApplication(ctx);
publicstaticvoid exitApplication(ConfigurableApplicationContext context) {
int exitCode = SpringApplication.exit(context, (ExitCodeGenerator) () -> 0);
System.exit(exitCode);
}
package com.hqs.springboot.shutdowndemo.controller;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
publicclassShutDownControllerimplementsApplicationContextAware{
privateApplicationContext context;
@PostMapping("/shutDownContext")
publicString shutDownContext() {
ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) context;
ctx.close();
return"context is shutdown";
}
@GetMapping("/")
publicString getIndex() {
return"OK";
}
@Override
publicvoid setApplicationContext(ApplicationContext applicationContext) throwsBeansException{
context = applicationContext;
}
}
总结一下:
原文链接:
https://www.cnblogs.com/huangqingshi/p/11370291.html
粉丝福利:实战springboot+CAS单点登录系统视频教程免费领取
???
?长按上方微信二维码 2 秒 即可获取资料
感谢点赞支持下哈
评论