1. 程式人生 > 程式設計 >雙十一還在蓋樓?少年你應該掌握Docker 部署 Consul了

雙十一還在蓋樓?少年你應該掌握Docker 部署 Consul了

img

▶ Spring Boot 依賴與配置

Maven 依賴

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        .....
        
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-config</artifactId>
        </dependency>

    </dependencies>
複製程式碼

▶ 使用說明

1、部署 Consul

  • 參考檔案:上一篇

2、在 resources 路徑下新增配置檔案 bootstrap.properties,示例如下:

# consul 基本配置
spring.cloud.consul.host=127.0.0.1
spring.cloud.consul.port=8500

# 啟用 consul 配置中心
spring.cloud.consul.config.enabled=true

# 基礎資料夾,預設值 config
spring.cloud.consul.config.prefix=config

# 應用資料夾,預設值 application,consul 會載入 config/<applicationName> 和 config/<defaultContext> 兩份配置,設定為相同值,則只加載一份
spring.cloud.consul.config.default-context=testApp
spring.application.name=testApp

# 環境分隔符,預設值 ","
spring.cloud.consul.config.profile-separator=-

# 配置轉碼方式,預設 key-value,其他可選:yaml/files/properties
spring.cloud.consul.config.format=properties

# 配置 key 值,value 對應整個配置檔案
spring.cloud.consul.config.data-key=data

# 啟用配置自動重新整理
spring.cloud.consul.config.watch.enabled=true

# 【疑問】請求 consul api 的延遲,單位:秒
spring.cloud.consul.config.watch.wait-time=1

# 重新整理頻率,單位:毫秒
spring.cloud.consul.config.watch.delay=10000複製程式碼

3、在 Consul Key/Value 中新增應用配置

配置項 spring.cloud.consul.config.prefix 指定了基本資料夾為 config,需要先建立資料夾 config

img

Tips:新建分兩種型別:資料夾、Key/Value,建立資料夾只需在後面加上 "/" 即可

配置項 spring.cloud.consul.config.default-contextspring.cloud.consul.config.profile-separator 指定了應用名和環境分隔符,例如應用 testApp 有環境 defaultdevprod,只需在 config

目錄下建立 testApptestApp-devtestApp-prod 三個資料夾即可:

img

配置項 spring.cloud.consul.config.format 指定了 Value 的轉化方式,依據個人喜好,可以配置為 yamlproperties,若選擇這兩種方式,需要配置 spring.cloud.consul.config.data-key,預設為 data,示例配置:

img

Tips:如需單獨配置每個 Key/Value,spring.cloud.consul.config.formatspring.cloud.consul.config.data-key 均不用設定

4、配置重新整理

spring.cloud.consul.config.watch.delay 設定了配置的重新整理間隔,在 Consul 修改了配置,會動態同步到應用內部。

▶ Github Demo URL

▶ 相關檔案

本文由部落格一文多發平臺 OpenWrite 釋出!