Spring Cloud Config是Spring Cloud团队建立的一个全新项目,用来为分布式系统中的基础设施和微服务应用提供集中化的外部配置支持,它分为服务端与客户端两个部分。其中服务端也称为分布式配置中心,它是一个独立的微服务应用,用来链接配置仓库并为客户端提供获取配置信息、加密/解密信息等访问接口;而客户端则是微服务架构中的各个微服务应用或基础设施,它们经过指定的配置中心来管理应用资源与业务相关的配置内容,并在启动的时候从配置中心获取和加载配置信息。Spring Cloud Config实现了对服务端和客户端中环境变量和属性配置的抽象映射,因此它除了适用于Spring构建的应用程序以外,也能够在任何其余语言运行的应用程序中使用。因为Spring Cloud Config实现的配置中心默认采用Git来存储配置信息,因此使用Spring Cloud Config构建的配置服务器,自然就支持对微服务应用配置信息的版本管理,而且能够经过Git客户端工具来方便的管理和访问配置内容。固然它也提供了对其余存储方式的支持,好比:SVN仓库、本地化文件系统。java
在本文中,咱们将学习如何构建一个基于Git存储的分布式配置中心,并对客户端进行改造,并让其可以从配置中心获取配置信息并绑定到代码中的整个过程。git
准备一个git仓库,能够在码云或Github上建立均可以。好比本文准备的仓库示例:http://git.oschina.net/didispace/config-repo-demoweb
假设咱们读取配置中心的应用名为config-client
,那么咱们能够在git仓库中该项目的默认配置文件config-client.yml
:spring
info: profile: default
config-client-dev.yml
:info: profile: dev
经过Spring Cloud Config来构建一个分布式配置中心很是简单,只须要三步:浏览器
config-server-git
,并在pom.xml
中引入下面的依赖(省略了parent和dependencyManagement部分):<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> </dependencies>
@EnableConfigServer
注解,开启Spring Cloud Config的服务端功能。@EnableConfigServer @SpringBootApplication public class Application { public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); } }
application.yml
中添加配置服务的基本信息以及Git仓库的相关信息,例如: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
,并得到以下返回:app
{ "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" } } ] }