首页 文章

如何关闭嵌入式jetty实例?

提问于
浏览
0

我有一个嵌入式jetty项目,它构建一个启动webapp的.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文件时,我们可以这样做:

  • 通过Jenkins构建最新的.war文件

  • 通过shell停止Jetty服务(sudo service jetty stop)

  • 使用新的.war文件覆盖 /opt/jetty/webapp 中的旧.war文件

  • 通过shell启动Jetty服务(sudo service jetty start)

我目前有两个想法:

  • 如果指定了secret get参数,则创建一个调用server.stop()的servlet . 在Jekins的shell上使用curl来命中这个servlet .

  • 使用类似Apache-Commons守护程序包装器的东西将我的应用程序变成服务 .

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

1 回答

  • 4

    使用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);
        }
    }
    

相关问题