java 程序化码头关闭
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5719159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatic Jetty shutdown
提问by Anton Kazennikov
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/shutdownHow do I do it cleanly?
现在,我想从请求中关闭它,例如http://127.0.0.1:8090/shutdown我该如何干净利落地做到这一点?
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.
通常建议的解决方案是创建一个线程并从该线程调用 server.stop()。但我可能需要调用 Thread.sleep() 以确保 servlet 已完成关闭请求的处理。
回答by James Anderson
I found a very clean neat method here
我在这里找到了一个非常干净整洁的方法
The magic code snippet is:-
神奇的代码片段是:-
server.setStopTimeout(10000L);;
try {
new Thread() {
@Override
public void run() {
try {
context.stop();
server.stop();
} catch (Exception ex) {
System.out.println("Failed to stop Jetty");
}
}
}.start();
Because the shutdown is running from a separate thread, it does not trip up over itself.
因为关闭是从一个单独的线程运行的,所以它不会被自己绊倒。
回答by Sven
Try server.setGracefulShutdown(stands_for_milliseconds);
.
试试server.setGracefulShutdown(stands_for_milliseconds);
。
I think it's similar to thread.join(stands_for_milliseconds);
.
我认为它类似于thread.join(stands_for_milliseconds);
.
回答by 01es
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.
不建议通过 HTTP 请求远程关闭 Jetty 服务器,因为这会带来潜在的安全威胁。在大多数情况下,通过 SSH 连接到托管服务器并在那里运行适当的命令来关闭 Jetty 服务器的相应实例就足够了。
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 call server.stop()
.
基本思想是启动一个单独的线程作为 Jetty 启动代码的一部分(因此不需要按照评论答案中提到的要求休眠),该线程将用作处理关闭请求的服务线程。在这个线程中,aServerSocket
可以绑定到 localhost 和一个指定的端口,当收到预期的消息时,它会调用server.stop()
.
Thisblog post provides a detailed discussion using the above approach.
这篇博文提供了使用上述方法的详细讨论。