使用ShutdownHandler关闭docker
我使用http://www.eclipse.org/jetty/documentation/current/shutdown-handler.html作为指导尝试关闭我的jetty服务器,但我得到java.net.SocketException: Unexpected end of file from server
connection.getResponseCode();
java.net.SocketException: Unexpected end of file from server
connection.getResponseCode();
被叫,我不知道为什么。 我正在使用xml配置的服务器,因此将ShutdownHandler添加到Handler链的方式略有不同,但应该没问题。 我知道ShutdownHandler已正确连接到处理程序链,因为我使用dumpAfterStartup来检查它是否已启动。
我最不确定的是行: URL url = new URL("http://localhost:" + port + "/shutdown?token=" + shutdownCookie);
。 我不知道我应该把什么放在shutdownCookie字段中; ShutdownHandler中指定的密码,或STOP键,或者是什么。 我已经尝试了密码和STOP键,没有运气。 我正在使用POST作为我的请求方法,但我也尝试了PUT,它也不起作用。
请根据需要提供更多信息。
shutdownCookie应该是您配置关闭处理程序的秘密
如果处理程序链配置正确,这将有效…
public void start() throws Exception { Server server = new Server(10100); DebugHandler dh = new DebugHandler(); dh.setHandler(new ShutdownHandler(server,"foo")); server.setHandler(dh); 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(); } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) { try { Shutdown s = new Shutdown(); s.start(); Shutdown.attemptShutdown(10100,"foobar"); } catch (Exception e) { e.printStackTrace(); } }
这会产生以下日志:
Aug 22, 2013 9:31:25 AM org.eclipse.jetty.server.Server doStart INFO: jetty-8.1.11.v20130520 Aug 22, 2013 9:31:25 AM org.eclipse.jetty.server.AbstractConnector doStart INFO: Started SelectChannelConnector@0.0.0.0:10100 Aug 22, 2013 9:31:25 AM org.eclipse.jetty.server.handler.ShutdownHandler handle WARNING: Unauthorized shutdown attempt from 127.0.0.1
将shutdownCookie从’foobar’更改为’foo’会产生:
2013-08-22 10:13:00.829:INFO:oejsh.ShutdownHandler:Shutting down by request from 127.0.0.1
您可以使用上面的代码并从另一个JVM调用静态方法,第一个服务器将按预期停止。
不幸的是,ShutdownHandler方法对我来说不起作用,但是我查看了源代码并找到了这个代码片段。
Socket s = new Socket(InetAddress.getByName("localhost"), STOP_PORT); try { OutputStream out = s.getOutputStream(); out.write((STOP_KEY + "\r\nstop\r\n").getBytes()); out.flush(); } finally { s.close(); }