Multiple datasources migrations using Flyway in a Spring Boot application

倖福魔咒の 提交于 2019-11-30 11:30:18

Flyway supports migrations coded within Java and so you can start Flyway during your application startup.

https://flywaydb.org/documentation/migration/java

I am not sure how you would config Flyway to target a number of data sources via the its config files. My own development is based around using Java to call Flyway once per data source I need to work against. Spring Boot supports the autowiring of beans marked as @FlywayDataSource, but I have not looked into how this could be used.

For an in-java solution the code can be as simple as

    Flyway flyway = new Flyway();

    // Set the data source
    flyway.setDataSource(dataSource);

    // Where to search for classes to be executed or SQL scripts to be found
    flyway.setLocations("net.somewhere.flyway");

    flyway.setTarget(MigrationVersion.LATEST);
    flyway.migrate();

To make @Roger Thomas answer more the Spring Boot way:

Easiest solution is to annotate your primary datasource with @Primary (which you already did) and just let bootstrap migrate your primary datasource the 'normal' way.

For the other datasources, migrate those sources by hand:

@Configuration
public class FlywaySlaveInitializer {

     @Autowired private DataSource dataSource2;
     @Autowired private DataSource dataSource3;
     //other datasources

     @PostConstruct
     public void migrateFlyway() {
         Flyway flyway = new Flyway();
         //if default config is not sufficient, call setters here

         //source 2
         flyway.setDataSource(dataSource2);
         flyway.setLocations("db/migration_source_2");
         flyway.migrate();

         //source 3
         flyway.setDataSource(dataSource3);
         flyway.setLocations("db/migration_source_3");
         flyway.migrate();
     }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!