如何在Spring Boot应用程序启动时启动H2 TCP服务器? [英] How to start H2 TCP server on Spring Boot application startup?

查看:1254
本文介绍了如何在Spring Boot应用程序启动时启动H2 TCP服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过在SpringBootServletInitializer主方法中添加以下行,我可以在运行app作为Spring Boot应用程序时启动H2 TCP服务器(文件中的数据库):

I'm able to start the H2 TCP server (database in a file) when running app as Spring Boot app by adding following line into the SpringBootServletInitializer main method:

@SpringBootApplication
public class NatiaApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        Server.createTcpServer().start();
        SpringApplication.run(NatiaApplication.class, args);
    }
}

但是如果我在Tomcat上运行WAR文件它不会不行,因为没有调用main方法。在bean初始化之前,如何在应用程序启动时启动H2 TCP服务器有更好的通用方法吗?我使用Flyway(autoconfig)并且它在Connection refused:connect上失败可能是因为服务器没有运行。谢谢。

But if I run the WAR file on Tomcat it doesn't work because the main method is not called. Is there a better universal way how to start the H2 TCP server on the application startup before beans get initialized? I use Flyway (autoconfig) and it fails on "Connection refused: connect" probably because the server is not running. Thank you.

推荐答案

此解决方案适合我。如果应用程序作为Spring Boot应用程序运行,并且如果它在Tomcat上运行,它将启动H2服务器。创建H2服务器作为bean不起作用,因为Flyway bean是先前创建的并且在Connection refused上失败。

This solution works for me. It starts the H2 server if the app runs as Spring Boot app and also if it runs on Tomcat. Creating H2 server as a bean did not work because the Flyway bean was created earlier and failed on "Connection refused".

@SpringBootApplication
@Log
public class NatiaApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        startH2Server();
        SpringApplication.run(NatiaApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        startH2Server();
        return application.sources(NatiaApplication.class);
    }

    private static void startH2Server() {
        try {
            Server h2Server = Server.createTcpServer().start();
            if (h2Server.isRunning(true)) {
                log.info("H2 server was started and is running.");
            } else {
                throw new RuntimeException("Could not start H2 server.");
            }
        } catch (SQLException e) {
            throw new RuntimeException("Failed to start H2 server: ", e);
        }
    }
}

这篇关于如何在Spring Boot应用程序启动时启动H2 TCP服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆