每次服務的代碼更新部署,不免會存在數據庫結構
的變動以及字典數據的添加
,手動執行更新腳本
是一個耗時耗力
的工做,並且還會出現遺漏或者其餘情況,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接口服務架構師