云代码会员 - 云代码空间
——
在本文中,我们将学习如何构建一个基于Git存储的分布式配置中心,并对客户端进行改造,并让其能够从配置中心获取配置信息并绑定到代码中的整个过程。
准备一个git仓库,可以在码云或Github上创建都可以。比如本文准备的仓库示例:http://git.oschina.net/didispace/config-repo-demo
假设我们读取配置中心的应用名为config-client,那么我们可以在git仓库中该项目的默认配置文件config-client.yml:
info: profile: default
|
info: profile: dev
|
通过Spring Cloud Config来构建一个分布式配置中心非常简单,只需要三步:
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> </dependencies>
|
@EnableConfigServer @SpringBootApplication public class Application { public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); } }
|
spring application: name: config-server cloud: config: server: git: uri: http://git.oschina.net/didispace/config-repo-demo/ server: port: 1201
|
到这里,使用一个通过Spring Cloud Config实现,并使用Git管理配置内容的分布式配置中心就已经完成了。我们可以将该应用先启动起来,确保没有错误产生,然后再尝试下面的内容。
如果我们的Git仓库需要权限访问,那么可以通过配置下面的两个属性来实现;
spring.cloud.config.server.git.username:访问Git仓库的用户名
spring.cloud.config.server.git.password:访问Git仓库的用户密码
完成了这些准备工作之后,我们就可以通过浏览器、POSTMAN或CURL等工具直接来访问到我们的配置内容了。访问配置信息的URL与配置文件的映射关系如下:
上面的url会映射{application}-{profile}.properties对应的配置文件,其中{label}对应Git上不同的分支,默认为master。我们可以尝试构造不同的url来访问不同的配置内容,比如,要访问master分支,config-client应用的dev环境,就可以访问这个url:http://localhost:1201/config-client/dev/master,并获得如下返回:
{ "name": "config-client", "profiles": [ "dev" ], "label": "master", "version": null, "state": null, "propertySources": [ { "name": "http://git.oschina.net/didispace/config-repo-demo/config-client-dev.yml", "source": { "info.profile": "dev" } }, { "name": "http://git.oschina.net/didispace/config-repo-demo/config-client.yml", "source": { "info.profile": "default" } } ] }
|
我们可以看到该Json中返回了应用名:config-client,环境名:dev,分支名:master,以及default环境和dev环境的配置内容。