有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring启动通知/严重错误后重启

我有一个Spring Boot应用程序,在ec2服务器上运行。 我不希望出现任何严重错误,但是,我想确保应用程序不会完全停止。例如,如果抛出OutOfMemory,JVM就会停止,而我对此一无所知

是否有办法配置应用程序/服务器,以便在出现任何严重错误时自动重新启动? 提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    你可以这样做:

    public static void main(String... args) throws Exception {
        while(true){
            try(ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args)) {
                CompletableFuture<Throwable> throwableFuture = new CompletableFuture<>();
                Thread.setDefaultUncaughtExceptionHandler(
                        (thread, throwable) -> throwableFuture.completeExceptionally(throwable));
                throwableFuture.get();
            } catch (Exception | VirtualMachineError t) {
                //log error
            }
        }
    }
    

    这将等待任何线程抛出未捕获的异常
    try with resources语句将关闭上下文并清理与之关联的任何资源
    然后,while循环将重新创建上下文

    您需要确保您创建的任何资源(如线程工厂)都在上下文关闭时被正确处理,否则您仍然会耗尽内存

    更好的方法是由systemd这样的外部服务管理器重新启动java服务