How to gracefully shutdown embeded jetty

jos picture jos · May 20, 2015 · Viewed 13.1k times · Source

I have an application runs on an embedded jetty server. Now i want to start/stop the server as a service. I use a script to start the server.

java $JAVA_OPTS -DREQ_JAVA_VERSION=$JAVA_VERSION -jar myjetty.jar

Main Class

Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(PORT);
server.addConnector(connector);
HandlerCollection handlers = new HandlerCollection();
NCSARequestLog requestLog = new NCSARequestLog();
requestLog.setFilename(home + "/logs/access_" + logFileDateFormat
            + ".log");
requestLog.setFilenameDateFormat(logFileDateFormat);
requestLog.setRetainDays(10);
requestLog.setAppend(true);
requestLog.setExtended(false);
requestLog.setLogCookies(false);
requestLog.setLogTimeZone(TimeZone.getDefault().getID());
RequestLogHandler requestLogHandler = new RequestLogHandler();
requestLogHandler.setRequestLog(requestLog);
handlers.addHandler(requestLogHandler);
server.setHandler(handlers);
server.start();
server.join();

This starts the server.Stopping and/or Restarting an embedded Jetty instance via web call can be used to stop server but, How to stop the server from the script? and what changes should i make to shout down server in the main class.

Answer

diginoise picture diginoise · Oct 3, 2017

Since Jetty 7.5.x you can use org.eclipse.jetty.server.handler.ShutdownHandler in your code:

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();

... which will allow you to shut down your jetty by issuing the following http POST request:

curl -X POST http://localhost:8080/shutdown?token=secret_password