美文网首页
Springboot flyway migrate执行完毕再执行

Springboot flyway migrate执行完毕再执行

作者: 鹅鹅鹅_ | 来源:发表于2019-05-25 18:19 被阅读0次

我在Springboot中同时集成了Akka actor和flyway。在WeatherActor中启动actor时执行了数据库查询写入等操作

@Override
    public void preStart() throws Exception {
        log.info(this.getClass().getSimpleName() + " preStart called");

        Duration timeout = Duration.create(2, TimeUnit.HOURS);
        getContext().setReceiveTimeout(timeout);

       //抓取天气数据,并存入数据库
        fetchWeatherData();

        super.preStart();
    }

然后启动测试程序,报错了。原因是flyway的migrate还未执行完毕,相关数据库表还没建立,然鹅actor已经启动,这个时候执行数据库相关查询当然会报错了。

org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "SUBSCRIBE" not found;

所以,我们的目标是在migrate执行完毕后再执行数据库相关操作。要实现这个目标,有两种方法(其他方法也有,需要你自己探索了)

  1. 使用DependsOn对相关Bean添加依赖,让数据库相关DAO Bean依赖flyway的Bean。这样DAO Bean初始化和使用就会在flyway Bean初始化之后了。
@DependsOn({"flyway", "flywayInitializer"})
@Component
public class UserDao {
}
  1. 继承FlywayMigrationStrategy。这种方式可以在migrate执行前后注入特定的操作。从执行日志也可以看到,真的起效果了,达到了我们的目标要求。
@Component
@Slf4j
public class CallbackFlywayMigrationStrategy implements FlywayMigrationStrategy {


    @Override
    public void migrate(Flyway flyway) {
        log.info("before flyway migration...");

        flyway.migrate();
       //fetchWeatherData();
        log.info("after flyway migration...");
    }

}

相关文章

网友评论

      本文标题:Springboot flyway migrate执行完毕再执行

      本文链接:https://www.haomeiwen.com/subject/cgszzqtx.html