You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:05:00