spring cloud config是spring cloud团队创建的一个全新的项目,用来为分布式系统中的基础设施和微服务应用提供集中化的外部配置支持,它分为服务端和客户端两部分。
服务端也被称为配置中心,其除了可以在spring构建的应用程序中使用也可以在其它语言运行的程序中使用。
构建配置中心:
新建项目命名为config-server并且添加config-server的依赖
主类中加入@EnableConfigServer注解,开启Spring Cloud Config的服务端功能
在application.properties中添加配置服务的基本信息以及Git仓库的相关信息
spring.application.name=config-server
server.port=7001
# 配置Git仓库位置
spring.cloud.config.server.git.uri=http://172.16.99.16/rxhan/test.git
# 配置仓库路径下的相对搜索位置
spring.cloud.config.server.git.searchPaths=config-repo
# Git仓库访问的用户名
spring.cloud.config.server.git.username=rxhan@travelsky.com
# Git仓库访问的密码
spring.cloud.config.server.git.password=12345678
到这里,使用一个通过Spring Cloud Config实现,并使用Git管理配置内容的分布式配置中心就完成了。启动项目。
配置规则详解:
为了验证配置中心,我们在Git仓库下创建config-repo如下目录
并根据环境创建出不同的文件
didispace.properties
didispace-dev.properties
didispace-test.properties
didspace-prod.properties
在四个配置文件中均设置一个from属性,并未每个配置文件分别设置不同的值
from=git-default-1.0
from=git-dev-1.0
from=git-test-1.0
from=git-prod-1.0
访问测试
http://localhost:7001/didispace/dev
客户端配置:
创建项目 config-client 并加入config依赖和web依赖
加入如下配置文件
bootstrap.properties
spring.application.name=didispace
spring.cloud.config.profile=dev
spring.cloud.config.label=master
spring.cloud.config.uri=http://localhost:7001/
server.port=7002
新建测试controller
访问测试
http://localhost:7002/from
至此基于spring cloud config的配置中心及客户端配置完成。