在微服务系统中,服务较多,相同的配置:如数据库信息、缓存、参数等,会出如今不一样的服务上,若是一个配置发生变化,须要修改不少的服务配置。spring cloud提供配置中心,来解决这个场景问题。
系统中的通用配置存储在相同的地址:GitHub,Gitee,本地配置服务等,而后配置中心读取配置以restful发布出来,其它服务能够调用接口获取配置信息。
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency>
这里注意读取文件的配置node
server: port: 9001 spring: application: name: config-server-9001 profiles: # 读取本地 # active: native # 读取Git active: git cloud: config: server: native: search-locations: classpath:/config git: # 读取的仓库地址 uri: https://gitee.com/cicadasmile/spring-cloud-config.git # 读取仓库指定文件夹下 search-paths: /cloudbaseconfig # 非公开须要的登陆帐号 username: password: label: master
不一样的环境读取的结果不一样。git
info: date: 20190814 author: cicada sign: develop version: V1.0
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
在上面的配置中心,配置读取Git资源,因此这里的配置也就是读取Git资源。github
server: port: 8001 spring: application: name: config-client-8001 profiles: active: dev cloud: config: # 读取本地配置 --------------------------- #uri: http://localhost:9001 ## 读取策略:快速失败 #fail-fast: true ## 读取的文件名:无后缀 #name: client-8001 ## 读取的配置环境 #profile: dev # client-8001-dev.yml # ---------------------------------------- # github上的资源名称 ----------------------- name: client-8001 # 读取的配置环境 profile: dev label: master # 本微服务启动后,经过配置中心6001服务,获取GitHub的配置文件 uri: http://localhost:9001 # ----------------------------------------
@RestController public class ClientController { @Value("${info.date}") private String date ; @Value("${info.author}") private String author ; @Value("${info.sign}") private String sign ; @Value("${info.version}") private String version ; /** * 获取配置信息 */ @RequestMapping("/getConfigInfo") public String getConfigInfo (){ return date+"-"+author+"-"+sign+"-"+version ; } }
上面的模式,经过服务中心,直接获取配置。下面把注册中心Eureka加进来。spring
启动顺序也是以下:数据库
node06-eureka-7001 config-server-9001 config-client-8001
完成后Eureka注册中心效果图,启动顺序以下:segmentfault
经过注册中心获取服务,避免使用URI地址。缓存
通过测试后,正确无误。restful
GitHub地址:知了一笑 https://github.com/cicadasmile/spring-cloud-base 码云地址:知了一笑 https://gitee.com/cicadasmile/spring-cloud-base