程序化 Jetty 关闭
如何以编程方式关闭嵌入式jetty服务器?
我像这样启动jetty服务器:
Server server = new Server(8090);
...
server.start();
server.join();
现在,我想根据请求关闭它,例如http://127.0。 0.1:8090/关机 我该如何干净利落地做呢?
通常提出的解决方案是创建一个线程并从该线程调用 server.stop()。 但我可能需要调用 Thread.sleep() 以确保 servlet 已完成处理关闭请求。
How to programmatically shutdown embedded jetty server?
I start jetty server like this:
Server server = new Server(8090);
...
server.start();
server.join();
Now, I want to shut it down from a request, such as http://127.0.0.1:8090/shutdown
How do I do it cleanly?
The commonly proposed solution is to create a thread and call server.stop() from this thread.
But I possibly need a call to Thread.sleep() to ensure that the servlet has finished processing the shutdown request.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现了一个非常干净整洁的方法这里
神奇的代码片段是:-
因为关闭是从一个单独的线程运行的,它不会自行失败。
I found a very clean neat method here
The magic code snippet is:-
Because the shutdown is running from a separate thread, it does not trip up over itself.
尝试
server.setGracefulShutdown(stands_for_milliseconds);
。我认为它类似于
thread.join(stands_for_milliseconds);
。Try
server.setGracefulShutdown(stands_for_milliseconds);
.I think it's similar to
thread.join(stands_for_milliseconds);
.不建议通过 HTTP 请求远程关闭 Jetty 服务器,因为这会带来潜在的安全威胁。在大多数情况下,通过 SSH 连接到托管服务器并在其中运行适当的命令来关闭 Jetty 服务器的相应实例就足够了。
基本思想是启动一个单独的线程作为 Jetty 启动代码的一部分(因此不需要按照评论答案中提到的其中之一的要求进行睡眠),该线程将作为服务线程来处理关闭请求。在此线程中,
ServerSocket
可以绑定到本地主机和指定端口,当收到预期消息时,它将调用server.stop()
。这篇博文提供了使用上述方法进行详细讨论。
Having the ability for a Jetty server to be shutdown remotely through a HTTP request is not recommended as it provides as potential security threat. In most cases it should be sufficient to SSH to the hosting server and run an appropriate command there to shutdown a respective instance of a Jetty server.
The basic idea is to start a separate thread as part of Jetty startup code (so there is no need to sleep as required in one of mentioned in the comment answers) that would serve as a service thread to handle shutdown requests. In this thread, a
ServerSocket
could be bound to localhost and a designated port, and when an expected message is received it would callserver.stop()
.This blog post provides a detailed discussion using the above approach.