严重错误时弹簧启动意外/重启

时间:2017-02-26 21:46:20

标签: java spring spring-boot

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

有没有办法以这种方式配置应用程序/服务器,如果发生任何严重错误,它会自动重启? 提前谢谢。

2 个答案:

答案 0 :(得分:0)

您可以向应用程序添加几个依赖项:

  • Spring-boot-starter-actuator:这会暴露很多endpoints来检查App状态,日志,获取线程转储等。
  • spring-cloud-context:这包含RestartEndpoint,您可以autowire进入您的应用程序,并公开API端点以重新启动应用程序。

完成后,您可以使用任何HTTP监控工具(如Spring Admin)来监控应用,并在需要时重新启动。

答案 1 :(得分:0)

您可以执行以下操作:

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循环将重新创建上下文。

您需要确保创建的所有资源(如线程工厂)并在上下文关闭时正确处理,否则您仍将耗尽内存。

更好的方法是让您的java服务由systemd等外部服务管理器重新启动。