Springboot集成Flyway(适用于多数据源)

1. Flyway

可以将初始化sql在项目启动时候执行,取代单独的DBN更新包

2. 依赖

<dependency>
		<groupId>org.flywaydb</groupId>
		<artifactId>flyway-core</artifactId>
		<version>5.2.1</version>
</dependency>

3. 配置说明(springboot配置版本)

配置名配置说明
flyway.baseline-description对执行迁移时基准版本的描述.
flyway.baseline-on-migrate当迁移时发现目标schema非空,而且带有没有元数据的表时,是否自动执行基准迁移,默认false.
flyway.baseline-version开始执行基准迁移时对现有的schema的版本打标签,默认值为1.
flyway.check-location检查迁移脚本的位置是否存在,默认false.
flyway.clean-on-validation-error当发现校验错误时是否自动调用clean,默认false.
flyway.enabled是否开启flywary,默认true.
flyway.encoding设置迁移时的编码,默认UTF-8.
flyway.ignore-failed-future-migration当读取元数据表时是否忽略错误的迁移,默认false.
flyway.init-sqls当初始化好连接时要执行的SQL.
flyway.locations迁移脚本的位置,默认db/migration.
flyway.out-of-order是否允许无序的迁移,默认false.
flyway.password目标数据库的密码.
flyway.schemas设定需要flywary迁移的schema,大小写敏感,默认为连接默认的schema.
flyway.sql-migration-prefix迁移文件的前缀,默认为V.
flyway.sql-migration-separator迁移脚本的文件名分隔符,默认__
flyway.sql-migration-suffix迁移脚本的后缀,默认为.sql
flyway.tableflyway使用的元数据表名,默认为schema_version
flyway.target迁移时使用的目标版本,默认为latest version
flyway.url迁移时使用的JDBC URL,如果没有指定的话,将使用配置的主数据源
flyway.user迁移数据库的用户名
flyway.validate-on-migrate迁移时是否校验,默认为true.

4. API方式集成

package com.hz.pro.artifact.config.migration;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

/**
 * @author pp_lan
 * @description
 */
@Component
@DependsOn({"dataSource", "slaveDataSource"})
public class DatabaseFlywayMigration {

    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseFlywayMigration.class);

    @Autowired
    private ApplicationContext context;

    @PostConstruct
    public void init() {

        initDataSource("dataSource");
        initDataSource("slaveDataSource");

    }

    public void initDataSource(String dataSourceName) {

        Flyway flyway = null;
        try {
            LOGGER.info("【初始化{}开始】", dataSourceName);

            DataSource dataSource = context.getBean(dataSourceName, DataSource.class);
            flyway = Flyway.configure()
                    .dataSource(dataSource)
                    .locations("/db/migration")
                    .table("t_version")
                    .encoding("utf-8")
                    .outOfOrder(true)
                    .baselineOnMigrate(true)
                    .validateOnMigrate(true)
                    .load();

            flyway.migrate();
            LOGGER.info("===========【初始化{}成功】===========", dataSourceName);

        } catch (FlywayException e) {
            if (flyway != null) {
                flyway.repair();
            }
            LOGGER.error("===========【初始化{}失败】===========", dataSourceName, e);
        }

    }

}

5. 屏蔽配置启动方式

springboot中默认使用flyway配置进行加载,使用api方式进行灵活配置时候需要将其(FlywayAutoConfiguration)进行屏蔽,不然会报错,部分报错信息屏蔽方式如下所示

5.1 报错信息

Caused by: java.lang.reflect.InvocationTargetException: null
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:70)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800)
	... 18 common frames omitted
Caused by: org.flywaydb.core.api.FlywayException: Found non-empty schema(s) `xxxx` without schema history table! Use baseline() or set baselineOnMigrate to true to initialize the schema history table.
	at org.flywaydb.core.Flyway$1.execute(Flyway.java:1371)
	at org.flywaydb.core.Flyway$1.execute(Flyway.java:1341)
	at org.flywaydb.core.Flyway.execute(Flyway.java:1696)
	at org.flywaydb.core.Flyway.migrate(Flyway.java:1341)
	... 25 common frames omitted

5.2 屏蔽方法

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

@SpringBootApplication(exclude = {FlywayAutoConfiguration.class})
public class HzBaseApplication {

	public static void main(String[] args) {
		SpringApplication.run(HzBaseApplication.class, args);
	}

}

6. 执行结果

6.1 日志

2023-05-25 10:23:22.596  INFO 161831 --- [           main] c.h.p.a.c.m.DatabaseFlywayMigration      : 【初始化dataSource开始】
2023-05-25 10:23:22.607  INFO 161831 --- [           main] o.f.c.internal.license.VersionPrinter    : Flyway Community Edition 5.2.1 by Boxfuse
2023-05-25 10:23:22.612  INFO 161831 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-05-25 10:23:22.917  INFO 161831 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2023-05-25 10:23:22.943  WARN 161831 --- [           main] o.f.c.internal.database.base.Database    : Flyway upgrade recommended: PostgreSQL 14.2 is newer than this version of Flyway and support has not been tested.
2023-05-25 10:23:23.140  INFO 161831 --- [           main] o.f.core.internal.command.DbValidate     : Successfully validated 1 migration (execution time 00:00.089s)
2023-05-25 10:23:23.291  INFO 161831 --- [           main] o.f.core.internal.command.DbMigrate      : Current version of schema "public": 1.0.0
2023-05-25 10:23:23.291  WARN 161831 --- [           main] o.f.core.internal.command.DbMigrate      : outOfOrder mode is active. Migration of schema "public" may not be reproducible.
2023-05-25 10:23:23.305  INFO 161831 --- [           main] o.f.core.internal.command.DbMigrate      : Schema "public" is up to date. No migration necessary.
2023-05-25 10:23:23.353  INFO 161831 --- [           main] c.h.p.a.c.m.DatabaseFlywayMigration      : ===========【初始化dataSource成功】===========
2023-05-25 10:23:23.353  INFO 161831 --- [           main] c.h.p.a.c.m.DatabaseFlywayMigration      : 【初始化slaveDataSource开始】
2023-05-25 10:23:23.368  INFO 161831 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Starting...
2023-05-25 10:23:23.526  INFO 161831 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Start completed.
2023-05-25 10:23:23.542  WARN 161831 --- [           main] o.f.c.internal.database.base.Database    : Flyway upgrade recommended: PostgreSQL 14.2 is newer than this version of Flyway and support has not been tested.
2023-05-25 10:23:23.709  INFO 161831 --- [           main] o.f.core.internal.command.DbValidate     : Successfully validated 1 migration (execution time 00:00.068s)
2023-05-25 10:23:23.885  INFO 161831 --- [           main] o.f.core.internal.command.DbMigrate      : Current version of schema "public": 1.0.0
2023-05-25 10:23:23.886  WARN 161831 --- [           main] o.f.core.internal.command.DbMigrate      : outOfOrder mode is active. Migration of schema "public" may not be reproducible.
2023-05-25 10:23:23.902  INFO 161831 --- [           main] o.f.core.internal.command.DbMigrate      : Schema "public" is up to date. No migration necessary.
2023-05-25 10:23:23.949  INFO 161831 --- [           main] c.h.p.a.c.m.DatabaseFlywayMigration      : ===========【初始化slaveDataSource成功】===========

6.2 数据库验证

 7. 扩展多数据源

多数据源通过buildConfiguration构建多个配置(数据源及script脚本),执行多次即可完成多数据源sql的初始化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值