Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gracefully shutdown embeded jetty

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.

like image 300
jos Avatar asked May 20 '15 10:05

jos


2 Answers

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
like image 141
diginoise Avatar answered Sep 22 '22 18:09

diginoise


You can call setStopTimeout(long timeout) to shutdown Jetty in a relatively graceful way. A statisticsHandler must be configured when calling this method.

Referencing: Jetty Server.class setStopTimeout(long)

e.g.

YourServletHandler servletHandler = new YourServletHandler();
StatisticsHandler statsHandler = new StatisticsHandler();
statsHandler.setHandler(servletHandler);

Server server = new Server(80);
server.setHandler(statsHandler);
server.setStopTimeout(3000L);

//...
server.start();

//...
server.stop();
like image 27
bjrara Avatar answered Sep 19 '22 18:09

bjrara