spring boot 优雅下线
作者:智慧源点
- 2024-06-15 北京
本文字数:1024 字
阅读完需:约 3 分钟
如果项目是 spring boot 微服务,注册中心是 nacos, 则先从 nacos 下线,然后 spring boot 在 shutdown, 代码如下:
@Endpoint(
id = "shutdownRegister"
)
@Configuration
@Slf4j
public class ShutdownRegisterEndpoint implements ApplicationContextAware {
private static final Map<String, String> NO_CONTEXT_MESSAGE = Collections.singletonMap("message", "No context to shutdownRegister.");
private static final Map<String, String> SHUTDOWN_MESSAGE = Collections.singletonMap("message", "Register Shutting down, bye...");
@Autowired(required = false)
NacosServiceRegistry nacosServiceRegistry;
@Autowired(required = false)
NacosRegistration registration;
private ConfigurableApplicationContext context;
@Autowired(required = false)
private ApplicationContext applicationContext;
public ShutdownRegisterEndpoint() {
log.info("[组件init]注销服务组件");
}
@WriteOperation
public Map<String, String> shutdownRegister() {
if (this.context == null) {
return NO_CONTEXT_MESSAGE;
}
if (nacosServiceRegistry != null && registration != null) {
log.info("注销nacos");
nacosServiceRegistry.deregister(registration);
}
if (applicationContext != null) {
applicationContext.publishEvent(new EleServerDownEvent(new Object()));
}
return SHUTDOWN_MESSAGE;
}
public void setApplicationContext(ApplicationContext context) throws BeansException {
if (context instanceof ConfigurableApplicationContext) {
this.context = (ConfigurableApplicationContext) context;
}
}
}
public class EleServerDownEvent extends ApplicationEvent {
private static final long serialVersionUID = 1305017141473336210L;
public EleServerDownEvent(Object source) {
super(source);
}
}
然后脚本启动命令如下:
curl --connect-timeout 5 -X POST http://$host_ip:18000/actuator/shutdownRegister
sleep 10
curl --connect-timeout 5 -X POST http://$host_ip:18000/actuator/shutdown
sleep 30
复制代码
划线
评论
复制
发布于: 刚刚阅读数: 5
智慧源点
关注
终身学习、研究java架构、ai大模型 2019-12-06 加入
商业合作: wytwhdwdd
评论