- 新增 FlywayConfig 类进行配置和初始化- 在 KLPApplication 中排除 FlywayAutoConfiguration - 更新 pom.xml 文件,添加 Flyway 相关依赖 - 创建第一个数据库迁移脚本 V2__create_test_table.sql
69 lines
2.3 KiB
Java
69 lines
2.3 KiB
Java
package com.klp.common.config;
|
|
|
|
import javax.annotation.Resource;
|
|
import javax.sql.DataSource;
|
|
|
|
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
|
|
import org.flywaydb.core.Flyway;
|
|
import org.flywaydb.core.api.output.MigrateResult;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.boot.CommandLineRunner;
|
|
import org.springframework.context.annotation.Bean;
|
|
import org.springframework.context.annotation.Configuration;
|
|
|
|
@Configuration
|
|
public class FlywayConfig {
|
|
|
|
@Value("${spring.profiles.active}")
|
|
private String activeProfile;
|
|
|
|
@Value("${spring.flyway.baseline-on-migrate}")
|
|
private boolean baselineOnMigrate;
|
|
|
|
@Value("${spring.flyway.locations}")
|
|
private String locations;
|
|
|
|
@Value("${spring.flyway.table}")
|
|
private String table;
|
|
|
|
@Resource
|
|
private DataSource dataSource;
|
|
|
|
@Bean
|
|
public Flyway flyway() {
|
|
DataSource masterDataSource = ((DynamicRoutingDataSource) dataSource).getDataSource("master");
|
|
System.out.println("masterDataSource class: " + masterDataSource.getClass().getName());
|
|
|
|
// // 如果想显式拿底层 HikariDataSource
|
|
// if (masterDataSource instanceof ItemDataSource) {
|
|
// masterDataSource = ((ItemDataSource) masterDataSource).getRealDataSource();
|
|
// }
|
|
|
|
System.out.println("masterDataSource class: " + masterDataSource.getClass().getName());
|
|
return Flyway.configure()
|
|
.dataSource(masterDataSource) // 注意这里是真实主库 DataSource
|
|
.baselineOnMigrate(baselineOnMigrate)
|
|
.locations(locations)
|
|
.table(table)
|
|
.load();
|
|
}
|
|
|
|
@Bean
|
|
public CommandLineRunner flywayRunner(Flyway flyway) {
|
|
return args -> {
|
|
System.out.println("========== 当前环境: " + activeProfile + " ==========");
|
|
System.out.println("========== 开始执行 Flyway 数据库迁移 ==========");
|
|
|
|
MigrateResult result = flyway.migrate();
|
|
System.out.println("迁移成功版本数: " + result.migrationsExecuted);
|
|
|
|
result.migrations.forEach(m -> {
|
|
System.out.println("执行版本: " + m.version + ",描述: " + m.description);
|
|
});
|
|
|
|
System.out.println("========== Flyway 数据库迁移完成 ==========");
|
|
};
|
|
}
|
|
}
|
|
|