如何关闭嵌入式码头实例?

How can you shut down an embedded jetty instance?

我有一个嵌入式 jetty 项目,它构建了一个启动我们的 web 应用程序的 .jar 文件。

public static void main(String[] args){            
            final Server server = new Server(threadPool);
            //Do config/setup code for servlets/database/contexts/connectors/etc
            server.start();
            server.dumpStdErr();
            server.join();
}

因此,虽然通过调用 java -jar MyApp.jar 启动我们的服务器效果很好,但我不知道如何停止它。当我想通过我们的构建服务器停止服务器时,这尤其烦人。

当我们使用 Jetty 服务并部署一个 .war 文件时,我们可以这样做:

  1. 通过 Jenkins 构建最新的 .war 文件
  2. 通过shell停止Jetty服务(sudo service jetty stop)
  3. 用新的 .war 文件
  4. 覆盖 /opt/jetty/webapp 中的旧 .war 文件
  5. 通过shell启动Jetty服务(sudo service jetty start)

我目前有两个想法:

  1. 如果您指定了秘密获取参数,请创建调用 server.stop() 的 servlet。在 Jekins 的 shell 上使用 curl 来命中这个 servlet。
  2. 使用类似于 Apache-Commons 守护程序包装器的东西将我的应用程序变成服务。

是否缺少一些明显的机制来停止服务器?

使用ShutdownHandler

服务器端:

Server server = new Server(8080);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]
{ someOtherHandler, new ShutdownHandler("secret password", false, true) });
server.setHandler(handlers);
server.start();

客户端(发出关闭命令)。

public static void attemptShutdown(int port, String shutdownCookie) {
    try {
        URL url = new URL("http://localhost:" + port + "/shutdown?token=" + shutdownCookie);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.getResponseCode();
        logger.info("Shutting down " + url + ": " + connection.getResponseMessage());
    } catch (SocketException e) {
        logger.debug("Not running");
        // Okay - the server is not running
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}