Config server的设计目的, 对一个系统来讲, 会有许多的service, 每个service都有一个配置文件(application.yml. application.properties). 当service很多时,管理和调整这些配置文件也是一件不简单的工作。
于是把service的配置文件放在一个地方,进行统一管理。可以是本地git 目录,也可以放在远程git上。Config server负责把配置文件发放给对应的service。
首先,建立一个config server项目。在pom.xml中加入:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> <version>2.2.6.RELEASE</version> </dependency> |
application.yml的配置如下:
server: port: 8002 spring: application: name: start-config-svr cloud: config: server: git: uri: https://github.com/xxx/yy username: aaaaaaa password: xxxxxxxx #basedir: /Users/Shared/myprj/git/yy label: master profile: dev eureka: client: service-url: defaultZone: http://localhost:8001/eureka/ management: endpoints: web: expose: "*" |
配置uri: https://github.com/xxx/yy指明了git repository的位置
此时可以在git repository中存储配置文件了。
label:指明了git分支,
profile:是应用的运行环境,如dev, uat, staging,不配置,则使用与service同名的缺省配置文件
git master分支下存储了两个配置文件:
start-client-cfg.yml
start-client-cfg-dev.yml
此时访问url:http://localhost:8002/start-client-cfg/dev, 则浏览器页面会显示两个配置文件
其次, 建立一个service, 在pom.xml中加入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
resource下建立一个配置文件,此时不能再用application.ym或application.properties,建立一个名字为bootstrap.yml的配置文件,用来定义service名称和config server
spring:
application:
name: start-client-cfg
cloud:
config:
uri: http://localhost:8002/
label: master
profile: dev
username: aaaaaaa
password: xxxxxxxx
application name 和git repository中的配置文件名一致,定义profile 环境
运行后,控制台显示:
Fetching config from server at : http://localhost:8002/
c.c.c.ConfigServicePropertySourceLocator : Located environment: name=start-client-cfg, profiles=[dev], label=master, version=b649d78eecd28057b42f0ea7d3dd6b66afc49645, state=null
service读取了配置服务器的配置文件,正常启动。