Consul 使用手册 - 配置管理
Consul 也能进行配置管理。
Spring Boot 配置管理与优先级
Spring Boot 多种配置方式
- 读取环境变量
server: port: ${SERVER_PORT}
java -jar xxx.jar --server.port=8083 SERVER_PORT java -jar xxx.jar http://localhost:8083/actuator/env http://localhost:8083/actuator/configprops
Profile
spring:
profiles:
active: dev
---
spring:
profiles: dev
---
spring:
profiles: prod
java -jar xxx.jar --spring.profiles.active=dev
java -jar xxx.jar --spring.profiles.active=dev,prod
使用Consul配置管理
为什么要使用配置服务器?
- 配置共享与重用
- 配置动态刷新
- …
创建 bootstrap.yml
application.yml
中所有的配置都可以交给 Consul 管理。
spring:
profiles:
active: dev
application:
name: micro-user
cloud:
consul:
host: localhost
port: 8500
config:
format: yaml
enabled: true
prefix: config
default-context: application
profile-separator: ','
data-key: data
watch:
enabled: true
delay: 1000
wait-time: 55
package cn.sbx0.micro.user.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Value("${first.config}")
private String firstConfig;
@GetMapping("/first-config")
public String test() {
return this.firstConfig;
}
}
引导上下文 Boostrap Context
Boostrap Context 是 Application Context 的父上下文, Spring Cloud 引入。
bootstrap.yml
就是引导上下文。
配置动态刷新 @RefreshScope
package cn.sbx0.micro.user.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RefreshScope
@RestController
public class TestController {
@Value("${first.config}")
private String firstConfig;
@GetMapping("/first-config")
public String test() {
return this.firstConfig;
}
}
配置刷新有一定的时延。那么希望立即生效那么该怎么做呢?只需要发送一个 POST 请求到 /actuator/refresh
。
Spring Cloud Consul 支持的配置格式
使用 git2consul 管理配置
git2consul(基于 Node.js 编写)可以用来将 Git 仓库中的数据,同步到 Consul
安装
npm install -g git2consul
配置
{
// 配置版本
"version": "1.0",
"repos": [
{
// 名称,指的是在consul里面的目录名称
"name": "config",
// 要同步的Git仓库
"url": "你的git仓库",
"branches": [
// 要同步的分支
"master"
],
// 是否要把分支名称作为Consul的key前缀
"include_branch_name": false,
"hooks": [
{
// 拉取模式
"type": "polling",
// 同步的间隔(分钟)
"interval": "1"
}
]
}
]
}
其他选项详见:https://github.com/breser/git2consul
启动
git2consul --config-file /Users/itmuch/develop/git2consul.json
配置优先级
Spring Boot 配置优先级
Spring Cloud 配置优先级
- {application}-{profile}.yml 指定 应用在 指定 环境的配置
- {application}.yml 指定 应用在 所有 环境的配置
- application-{profile}.yml 所有 应用在 指定 环境下的配置
- application.yml 所有 应用在 所有 环境下的配置
远程配置与本地配置的优先级
- 默认情况下远程配置优先级更高
- ps:以下三个配置必须存放在远程才有效
spring: cloud: config: # 是否允许本地配置覆盖远程配置 allow-override: true # 是否一切以本地配置为准,默认 false override-none: false # 系统环境变量或系统属性才能覆盖远程配置文件的配置 # 本地配置文件中配置优先级低于远程配置,默认 true override-system-properties: true
配置管理最佳实践
- 能放本地,就不放在远程上
- 尽量规避优先级
- 制定配置规范,必须添加注释
其他
mvn clean install -DskipTests