本文作者:suxingrui
本文链接:https://blog.csdn.net/suxingrui/article/details/122104281
版权声明:本文为原创文章,转载请注明出处。
问题:Failed to stop bean 'nacosWatch’
问题:
kill -15 停止服务的时候抛出异常:
导致timeout of 30000ms,即服务需要等待30秒超时之后才能正常停止
分析:
看空指针异常的抛出点,跟对照日志可以知道,问题出现的原因是:
undertow比nacos watch先shutdown,从而导致在nacos watch停止时获取不到相关对象
解决:
只需要nacos watch比undertow优先shutdown
查看了SpringContextShutdownHook的代码,暂时不知道能不能调整shutdown的优先级
所以自己写了个ShutdownHook来提高优先级:
@Slf4j
@Component
public class NacosStopHelper implements InitializingBean {
@Autowired
private NacosWatch nacosWatch;
@Autowired
private NacosAutoServiceRegistration nacosAutoServiceRegistration;
@Override
public void afterPropertiesSet() throws Exception {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
if (nacosWatch != null) {
log.info("Shutting down NacosWatch");
try {
nacosWatch.stop();
} catch (Exception e) {
log.info("Shutting down NacosWatch fail!", e);
}
}
if (nacosAutoServiceRegistration != null) {
log.info("Shutting down NacosAutoServiceRegistration");
try {
nacosAutoServiceRegistration.stop();
} catch (Exception e) {
log.info("Shutting down NacosAutoServiceRegistration fail!", e);
}
}
}));
}
}
PS:
以下日志的空指针,是一样的问题导致,所以nacosAutoServiceRegistration也同样写到自定义的ShutdownHook
[SpringContextShutdownHook] WARN [o.s.c.annotation.CommonAnnotationBeanPostProcessor:185] - Destroy method on bean with name ‘nacosAutoServiceRegistration’ threw an exception: java.lang.NullPointerException