Spring|Spring Cloud系列四 之 配置信息Server

小伙伴我刚接触的时候,一脸懵逼,心多有很多疑惑。经历了一周断断续续的开发和学习终于有所头目,故分享给大家,希望大家学习路上少走弯路。
本篇文章,通过提出问题的形式,在带领大家一步一步解决问题。
问题一:如何创建配置信息服务器
  • 注意两点
    • 1.让配置信息服务器默认从本地文件夹中获得配置信息
    • 2.让配置信息服务器从github或者码云中读取配置信息
    • 3.应用启动要引入那些依赖,pom文件是什么样
1: #从本地文件夹中读取,默认是src/main/resource spring.profiles.active=native

2: #从服务器中读取 # github服务器中的个人仓库 spring.cloud.config.server.git.uri=http://git.oschina.net/didispace/SpringBoot-Learning/ #从仓库中选择的配置目录 spring.cloud.config.server.git.searchPaths=Chapter9-1-4/config-repo #登录用户名 spring.cloud.config.server.git.username=username #用户密码 spring.cloud.config.server.git.password=password

只要引入这个依赖就可以
">org.springframework.cloud spring-cloud-config-server

  • 完整POM文件
4.0.0com.didispace config-server 1.0.0jarconfig-server Spring Cloud projectorg.springframework.boot spring-boot-starter-parent 1.3.5.RELEASE UTF-8 1.8 org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-config-server org.springframework.cloud spring-cloud-dependencies Brixton.RELEASE pom import org.springframework.boot spring-boot-maven-plugin

问题二:其他项目如何读取 配置服务器中的配置
  • 注意不能使用application.properties
上面这些属性必须配置在bootstrap.properties中,config部分内容才能被正确加载。因为config的相关配置会先于application.properties
  • 创建bootstrap.properties配置,来指定config server,例如:
#读取的问题名 spring.application.name=didispace #读取的文件环境 spring.cloud.config.profile=dev #配置文件所在的分支 spring.cloud.config.label=master #配置服务器地址 spring.cloud.config.uri=http://localhost:7001/ #当前项目的启动端口 server.port=7002

问题三:重点来了,配置文件如何命名,服务器才能正确读取
  • URL与配置文件的映射关系如下:
    • /{application}/{profile}[/{label}]
    • /{application}-{profile}.yml
    • /{label}/{application}-{profile}.yml
    • /{application}-{profile}.properties
    • /{label}/{application}-{profile}.properties
问题四:如何从配置服务器中 请求获得不同环境的配置信息
  • 我们可以尝试构造不同的url来访问不同的配置内容,比如:要访问config-label-test分支,didispace应用的prod环境,可以通过这个url:http://localhost:7001/didispace/prod/config-label-test
  • http://localhost:7001/didispace/{profile环境}/{lable分支}
{ "name": "didispace", "profiles": [ "test" ], "label": "master", "version": null, "propertySources": [ { "name": "classpath:/didispace-test.properties", "source": { "from": "local-test" } }, { "name": "classpath:/didispace.properties", "source": { "from": "local" } } ] }

问题五:实时刷新配置
  • 【Spring|Spring Cloud系列四 之 配置信息Server】如何实时刷新,修改git仓库中的配置信息,实时更新到应用中
  • 然后在配置服务器:http://localhost:7002/refresh
    • refresh接口要引入节点依赖
1 2org.springframework.boot 3spring-boot-starter-actuator 4

    推荐阅读