关闭/从 Servlet 取消部署 tomcat
我在 Tomcat 中有一个加载关键数据的 init servlet。有时需要因某些错误而中止启动。
我如何在不调用 System.exit(1) 的情况下优雅地关闭已部署的应用程序/整个应用程序服务器
我想避免通过端口调用关闭 servlet,因为这在我的安装中没有配置。
可能有一些任务需要在 web.xml 中定义的关闭时从侦听器运行
I have an init servlet in Tomcat that loads critical data. Sometimes it is necessary to abort startup on certain errors.
how do i gracefully shutdown the deployed app/ the whole app server without calling System.exit(1)
i want to avoid calling the shutdown servlet via port, since this is not configured in my installation.
there may be tasks that need to be run from listeners on shutdown defined in web.xml
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您永远不应该从 servlet 容器内调用
System.exit()
,因为可能有其他应用程序与您的应用程序在同一进程中运行,并且这是非常不正确的强行杀死整个进程。假设您的“init servlet”实现了 ServletContextListener,则 API/接口中没有定义正式的方法来向 servlet 容器发出信号“请彻底关闭应用程序”。但是,您可以从
contextInitialized()
方法中抛出某种RuntimeException
,在大多数容器(至少 Tomcat)中,该方法将停止您的 Web 应用程序的启动并将其保留在“停止”状态。但是我怀疑 Tomcat 是否会继续调用您的关闭侦听器。您可能需要重新考虑您的设计,以便您的关键数据/关闭逻辑不会与 servlet 容器的生命周期紧密相关。
First of all, you should never ever ever ever call
System.exit()
from within a servlet container, as there might be other applications running within the same process as yours, and it would be incredibly incorrect to forcibly kill the entire process.Assuming your "init servlet" implements
ServletContextListener
, there is no formal way defined in the API/interface to signal to the servlet container "please shut down the app neatly". You could however throw some sort ofRuntimeException
from thecontextInitialized()
method, which in most containers (at least Tomcat) will stop the startup of your webapp and leave it in the "stopped" state. However I doubt that Tomcat will continue to call your shutdown listeners.You might want to rethink your design so that your critical data / shutdown logic is not tied so tightly with the lifecycle of the servlet container.
我添加的是一个运行状况检查探针,它将使用
curl
检查服务器是否仍在运行,我认为可以对其进行修改以检查“标志”文件是否也存在。我只是发送一个catalina.sh stop
命令。如果这是一个 Docker 容器,您也可以使用运行状况检查探针让它自行关闭。
理想情况下,如果您可以迁移到 Spring Boot 之类的东西,它运行 tomcat,但如果 Spring Context 未正确加载,则终止它。
What I added was a healthcheck probe that would check if the server was still up using a
curl
I think it can be modified to check if a "flag" file is present as well. I just send acatalina.sh stop
command.If this was a Docker container, you can use the healthcheck probe to let it close itself as well.
Ideally if you can migrate to something like Spring Boot which runs tomcat but terminates it if the Spring Context does not load properly.