Spring Cloud Config 原理

我们通过git 把配置文件推送到远程仓库做版本控制,当版本发生变化的时候,远程仓库通过webhook机制推送消息给 Config Server,Config Server 将修改通知发送到消息总线,然后所有的Config Client 进行配置刷新。
非常巧妙的借助了Git来做配置文件修改的版本控制。
Consul Config 的FILES 机制
1public enum Format { 2 /** 3 * Indicates that the configuration specified in consul is of type native key values. 4 */ 5 KEY_VALUE, 6 7 /** 8 * Indicates that the configuration specified in consul is of property style i.e., 9 * value of the consul key would be a list of key=value pairs separated by new lines. 10 */ 11 PROPERTIES, 12 13 /** 14 * Indicates that the configuration specified in consul is of YAML style i.e., value 15 * of the consul key would be YAML format 16 */ 17 YAML, 18 19 /** 20 * Indicates that the configuration specified in consul uses keys as files. 21 * This is useful for tools like git2consul. 22 */ 23 FILES, 24 25}
Consul 提供以上的策略,key/value、yaml、properties,可以很简单的通过Consule Config 的管理台进行配置,我们主要来看FILES,就是我们也是Cloud Config 一样,通过Git 来做版本控制,只是用Consul 做配置的分发和修改的通知。 原生的Consul不支持Git来做,需要借助Consul 社区提供的另外一个工程 git2consul 非常简单就下载就安装好了。
主要来讲一下初始化脚本的 git2consul.json
1{ 2 "version":"1.0", 3 "local_store": "本地仓库备份地址", 4 "logger":{ 5 "name":"git2consul", 6 "streams":[ 7 { 8 "level":"trace", 9 "type":"rotating-file", 10 "path":"生成日志路径/git2consul.log" 11 } 12 ] 13 }, 14 "repos":[ 15 { 16 "name":"pig-config", 17 "url":"远程仓库地址", 18 "include_branch_name" : true, //分支信息是否包含到请求中,建议使用 19 "branches":[ 20 "dev" 21 ], 22 "hooks":[ 23 { 24 "type" : "polling", //更新策略定时刷新的 25 "interval" : "1" //1分钟 26 } 27 ] 28 } 29 ] 30} 31
启动时候指定上边的脚本
./git2consul --config-file git2consul.json
bootstarp.yml配置
1spring: 2 application: 3 name: pig-auth 4 cloud: 5 consul: 6 host: localhost 7 port: 8500 8 config: 9 enabled: true 10 format: FILES 11 watch: 12 enabled: true 13 prefix: ${spring.application}/${spring.profiles.active} 14 profiles: 15 active: dev
OK 已经可以使用了 git2consul 来同步你的配置文件啦。
配置细节

如上图,我配置文件的例子。
FILES机制和Spring Cloud Config加载类似,application.yml 会被所有微服务模块加载公用,对应的application-name.yml 会被对应的微服务加载。
总结
- 经过整合Consul Config 已经完成了和Spring Cloud Config 相同的功能,Spring Cloud 微服务使用配置文件过程中并没有太大区别。
- 实时刷新机制和前文《Consul微服务的配置中心体验篇》提到的KEY-VALUE模式没有什么区别,git2consul 不仅支持webhook 的push,而且可以轮询pull,类似于 Apollo 配置中心的部分功能
- 关于pig:基于Spring Cloud、oAuth2.0开发基于Vue前后分离的开发平台,支持账号、短信、SSO等多种登录,提供配套视频开发教程