在不重启服务器的情况下启动或停止码头 ServerConnector

Start or Stop a jetty ServerConnector without server restart

我使用 Jetty 服务器来处理客户端请求,并且有一个要求,我需要根据需要启动或停止一个或几个 ServerConnector,而无需重新启动这些连接器所连接的服务器。

例如

ServerConnector httpConnector;
ServerConnector httpsConnector;
Server server;
server.addConnector(httpConnector);
server.addConnector(httpsConnector);
server.start()

需要 start/stop/cancel 特定的连接器而不强制服务器重新启动。

您可以在连接器上调用 stop 来停止它,然后调用 start 来重新启动它。要获得相关连接器,有两种解决方案:

  • 将创建的连接器实例保存在某处并调用方法
  • 通过调用 getConnectors 获取服务器的所有连接器,遍历它们,找到您要停止的连接器并在其上调用 stopstart 来停止或启动它.

您必须执行以下操作...

// TODO: Have a reference to the Connector you are going to work with

// Remove from server first.
server.removeConnector(connector);

// Stop the connector.
// NOTE: Existing connections will still live on.  
// This will only stop accepting new connections.
connector.stop(); // might take a while (waiting for acceptors to close)

// TODO: do what you want with this connector

// Eg: harshly close existing connections
connector.getConnectedEndPoints().forEach((endpoint)-> {
    endpoint.close();
});

// Re-add stopped connector if you want
// This will start connector as well
// This can fail (eg: if port is already in use)
server.addConnector(connector);