每次服务的代码更新部署,不免会存在数据库结构
的变动以及字典数据的添加
,手动执行更新脚本
是一个耗时耗力
的工做,并且还会出现遗漏或者其余情况,SpringBoot
内部集成了一个自动执行数据库脚本的第三方依赖Flyway
来解决这个繁琐的问题。java
官网给出的定义是`Version control for your database.Robust schema evolution across all your environments.With ease, pleasure and plain SQL.`(数据库的版本控制,在全部环境中进行稳健的架构演变,轻松,愉快和简单的SQL。)mysql
Flyway
是一款开源的数据库版本管理工具,它更倾向于规约优于配置的方式。spring
Flyway
能够独立于应用实现管理并跟踪数据库变动,支持数据库版本自动升级,而且有一套默认的规约,不须要复杂的配置,Migrations
能够写成 SQL 脚本
,也能够写在 Java 代码中,不只支持 Command Line
和 Java API
,还支持 Build 构建工具和 Spring Boot
等,同时在分布式环境下可以安全可靠地升级数据库
,同时也支持失败恢复
等。sql
当咱们运行配置使用Flyway
的应用程序时,会自动在配置数据源的数据库内建立一个名为flywayschemahistory的表,该表内存放了数据库的历史记录
信息。而后经过扫码应用程序的
/reosurces/db/migration
目录下的历史版本脚本SQL文件,文件格式为:V?__desc.sql
,如:V1__init-db.sql
,根据版本号进行排序后,获取最大的版本号与flyway_schema_history
表内执行成功的最大版本号进行比对,若是项目内版本较高,则自动执行脚本文件。数据库
经过idea
工具建立SpringBoot
项目,在pom.xml
添加相关依赖以下所示:api
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>复制代码
在application.yml
配置文件内添加数据源信息,以下所示:安全
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/flyway
username: root
password: 123456
type: com.zaxxer.hikari.HikariDataSource复制代码
脚本比较简单,你们能够任意添加一些SQL来查看结构或者数据变更。架构
db.migration
目录是SpringBoot
在整合Flyway
时默认读取版本脚本的目录,咱们能够在application.yml
配置spring.flyway.locations
参数进行修改。app
当咱们启动项目时,会自动比对脚本的版本,在db.migration
目录内找到V1.1__add_logging.sql
为最高版本,拿着1.1
再去flyway_schema_history
表内执行成功最大的版本比对,若是低于1.1
则自动执行V1.1_add_logging.sql
脚本内容,不然跳过。框架
每次启动项目若是存在可更新的脚本信息,执行完成后会自动在flyway_schema_history
表内添加一条记录。
installed_rank | version | description | type | script |
checksum |
installed_by | installed_on |
execute_time | success |
---|---|---|---|---|---|---|---|---|---|
1 |
1 |
init |
SQL |
V1__init.sql |
2034194600 | root |
2019-10-23 21:44:36 | 17 |
1 |
2 |
1.1 |
add logging | SQL |
V1.1addlogging.sql | 1859098444 | root |
2019-10-23 21:46:50 | 54 |
1 |
本章简单的介绍了Flyway
的基本使用方法,它很强大,功能远远不止于此,使用脚本统一自动执行可大大减小手动执行出现的遗漏、错误等。存在既有道理,为何不尝试使用呢?
做者我的 博客
使用开源框架 ApiBoot 助你成为Api接口服务架构师