如何在Helidon SE 4(Nima)中设置服务器关闭钩子?
在Helidon SE 4中设置服务器关闭钩子的方法
Helidon SE 4移除了SE 3版本中的server.whenShutdown()方法,要实现服务器关闭后的回调逻辑,可以通过以下方式替代:
原Helidon SE 4启动代码
public static void main(final String[] args) { // load logging configuration LogConfig.configureRuntime(); // initialize global config from default configuration Config config = Config.create(); Config.global(config); // Get webserver config from the "server" section of application.yaml WebServerConfig.Builder builder = WebServer.builder(); WebServer server = builder .config(config.get("server")) .routing(Main::routing) .build() .start(); System.out.println("WEB server is up! http://localhost:" + server.port() + "/greet"); }
Helidon SE 3中的旧实现方式
server.whenShutdown().thenRun(() -> System.out.println("WEB server is DOWN. Good bye!"));
Helidon SE 4的替代方案
利用WebServer.shutdown()返回的CompletionStage<Void>结合JVM关闭钩子,实现服务器关闭后的回调:
public static void main(final String[] args) { // load logging configuration LogConfig.configureRuntime(); // initialize global config from default configuration Config config = Config.create(); Config.global(config); // Get webserver config from the "server" section of application.yaml WebServerConfig.Builder builder = WebServer.builder(); WebServer server = builder .config(config.get("server")) .routing(Main::routing) .build() .start(); System.out.println("WEB server is up! http://localhost:" + server.port() + "/greet"); // 注册JVM关闭钩子,监听服务器关闭完成事件 Runtime.getRuntime().addShutdownHook(new Thread(() -> { server.shutdown() .thenRun(() -> System.out.println("WEB server is DOWN. Good bye!")) .exceptionally(ex -> { System.err.println("服务器关闭失败: " + ex.getMessage()); return null; }); })); }
说明:当JVM收到关闭信号时,会触发注册的关闭钩子,调用server.shutdown()关闭服务器,通过thenRun()注册关闭完成后的逻辑,exceptionally()则用于处理关闭过程中可能出现的异常。
内容的提问来源于stack exchange,提问作者Ansar Ozden
相关产品推荐
相关产品推荐

