简体   繁体   English

如何在 Spring Boot 应用程序中和使用 flyway 启动 H2 db TCP 服务器

[英]How to start H2 db TCP server within Spring Boot application and with flyway

I use Spring Boot and H2 db with Flyway, and I want to start the H2 db tcp server upon start of my application (written in Spring Boot).我将 Spring Boot 和 H2 db 与 Flyway 一起使用,并且我想在我的应用程序启动时启动 H2 db tcp 服务器(用 Spring Boot 编写)。

So I have such application.properties file.所以我有这样的application.properties文件。

db.port=9090
spring.datasource.url=jdbc:h2:tcp://localhost:${db.port}/./database/ifin-relax
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.driver-class-name=org.h2.Driver

flyway.baseline-on-migrate=true
flyway.url=jdbc:h2:tcp://localhost:${db.port}/./database/ifin-relax
flyway.table=SCHEMA_VERSION
flyway.user=sa
flyway.password=password

And also I have the following configuration class for h2 db server.而且我还有以下 h2 db 服务器的配置类。

@Configuration
public class H2DBServerConfiguration {

    @Value("${db.port}")
    private String h2DbPort;

    @Bean
    public Server server() throws SQLException {
        return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", h2DbPort).start();
    }
}

But when I run the application it fails with exception但是当我运行应用程序时它失败了

Error creating bean with name 'flywayInitializer' defined in class path resource

It seems that flyway tries to apply migrations even before H2's TCP server was instantiated.似乎 flyway 甚至在 H2 的 TCP 服务器被实例化之前就尝试应用迁移。 So the question is how to postpone flyway migrations until the DB Server is started?所以问题是如何推迟flyway迁移直到DB Server启动?

I found a solution:我找到了一个解决方案:

@Configuration
public class H2ServerConfiguration {

    @Value("${db.port}")
    private String h2TcpPort;

   /**
    * TCP connection to connect with SQL clients to the embedded h2 database.
    *
    * @see Server
    * @throws SQLException if something went wrong during startup the server.
    * @return h2 db Server
    */
    @Bean
    public Server server() throws SQLException {
        return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", h2TcpPort).start();
    }

    /**
     * @return FlywayMigrationStrategy the strategy for migration.
     */
     @Bean
     @DependsOn("server")
     public FlywayMigrationStrategy flywayMigrationStrategy() {
         return Flyway::migrate;
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM