双十一还在盖楼?少年你应该掌握Docker 部署 Consul了

时间:2024-04-18 20:08:36

双十一还在盖楼?少年你应该掌握Docker 部署 Consul了

▶ 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

双十一还在盖楼?少年你应该掌握Docker 部署 Consul了

Tips:新建分两种类型:文件夹、Key/Value,创建文件夹只需在后面加上 "/" 即可

配置项 spring.cloud.consul.config.default-contextspring.cloud.consul.config.profile-separator 指定了应用名和环境分隔符,例如应用 testApp 有环境 defaultdevprod,只需在 config 目录下创建 testApptestApp-devtestApp-prod 三个文件夹即可:

双十一还在盖楼?少年你应该掌握Docker 部署 Consul了

配置项 spring.cloud.consul.config.format 指定了 Value 的转化方式,依据个人喜好,可以配置为 yamlproperties,若选择这两种方式,需要配置 spring.cloud.consul.config.data-key,默认为 data,示例配置:

双十一还在盖楼?少年你应该掌握Docker 部署 Consul了

Tips:如需单独配置每个 Key/Value,spring.cloud.consul.config.formatspring.cloud.consul.config.data-key 均不用设置

4、配置刷新

spring.cloud.consul.config.watch.delay 设置了配置的刷新间隔,在 Consul 修改了配置,会动态同步到应用内部。

▶ Github Demo URL

▶ 相关文档

双十一还在盖楼?少年你应该掌握Docker 部署 Consul了

本文由博客一文多发平台 OpenWrite 发布!