为了账号安全,请及时绑定邮箱和手机立即绑定

Spring-boot:在不启动应用程序的情况下运行flyway迁移

Spring-boot:在不启动应用程序的情况下运行flyway迁移

largeQ 2024-01-05 10:03:44
我们有一个 Spring Boot 服务,可以进行 Flyway 迁移,并且一切正常。现在,对于新的部署用例,问题是是否有一个 java 选项(参数或类似的东西)来仅启动 Flyway 迁移而不启动实际服务。
查看完整描述

3 回答

?
波斯汪

TA贡献1811条经验 获得超4个赞

这对我来说很有用;


import static org.springframework.boot.WebApplicationType.NONE;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.SpringBootConfiguration;

import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;

import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

import org.springframework.boot.builder.SpringApplicationBuilder;

import org.springframework.context.annotation.Import;


/**

 * Utility to run flyway migration without starting service

 */

@SpringBootConfiguration

@Import({DataSourceAutoConfiguration.class, FlywayAutoConfiguration.class})

public class FlywayMigrationRunner {


public static void main(String[] args) {


SpringApplication application =

    new SpringApplicationBuilder(FlywayMigrationRunner.class)

        .web(NONE).build();


    application.run(args);

  }

}

中等链接


查看完整回答
反对 回复 2024-01-05
?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

基本上,我自己通过利用 Flyway 回调来实现它,并在迁移成功完成后简单地关闭应用程序。整个过程由一个单独的配置参数控制。


这是回调


public class PostMigrationCallback implements Callback {


  private final FlywayCustomProperties flywayCustomProperties;

  private final ApplicationContext applicationContext;


  public PostMigrationCallback(FlywayCustomProperties flywayCustomProperties, ApplicationContext applicationContext) {

    this.flywayCustomProperties = flywayCustomProperties;

    this.applicationContext = applicationContext;

  }


  @Override

  public boolean supports(Event event, Context context) {

    if (event.getId().equalsIgnoreCase("afterMigrate") && flywayCustomProperties.isMigrationOnly()) {

      log.info("Service is going to shutdown as configuration was set to spring.flyway.migrate-only=true and schema was migrated successfully");

      int exitCode = SpringApplication.exit(applicationContext, () -> 0);

      System.exit(exitCode);

    }

    return false;

  }


  @Override

  public boolean canHandleInTransaction(Event event, Context context) {

    return false;

  }


  @Override

  public void handle(Event event, Context context) {

  }

}

这里我们有配置参数


@Data

@Validated

@ConfigurationProperties(prefix = "spring.flyway")

public class FlywayCustomProperties {


  @NotNull

  private boolean migrationOnly;

}


查看完整回答
反对 回复 2024-01-05
?
富国沪深

TA贡献1790条经验 获得超9个赞

是的,您可以使用 Flyway cli 来运行迁移,而无需启动服务: https ://flywaydb.org/documentation/commandline/


查看完整回答
反对 回复 2024-01-05
  • 3 回答
  • 0 关注
  • 163 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信