首页 > 技术文章 > Spring生态系列文章 >

SpringCloud极简入门(十一)Spring Cloud Config(Config Client)

更新时间:2018-08-20 | 阅读量(914)

接下来我们需要搭建Config Client 客户端来访问 Config Server从git中获取的配置参数 ###搭建客户端应用 >1.创建SpringBoot应用ConfigClient,pom文件如下 ``` org.springframework.boot spring-boot-starter-parent 2.0.3.RELEASE UTF-8 UTF-8 1.8 Finchley.RELEASE org.springframework.cloud spring-cloud-starter-config org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import ``` >2.主程序配置类不做任何修改,如下 ``` @SpringBootApplication public class ConfigClientApplication { public static void main(String[] args) { SpringApplication.run(ConfigClientApplication.class, args); } } ``` >3.修改配置文件 application.properties,只需要一个应用名即可 ``` spring.application.name=config-client ``` >4.创建配置文件 bootstrap.properties,内容如下 ``` #分支 spring.cloud.config.label=master #指定dev开发环境配置文件 dev开发环境配置文件 spring.cloud.config.profile=dev #指定配置文件名字 config-client,此名字对应git中的配置文件的名字 spring.cloud.config.name=config-client #配置服务地址,执行我们上一章的ConfigServer服务地址 spring.cloud.config.uri=http://localhost:5555/ ``` 这里我们在resources目录下搞了两个配置文件,一个是默认的application.properties,一个是bootstrap.properties,这两个文件都可以作为SpringBoot的配置,只是bootstrap.properties中的配置优先级高于前者,而bootstrap.properties一般用来加载外部配置, config.label=master :指定使用git主分支, config.uri=http://localhost:5555/ :指定配置服务地址, config.name=config-client:指定git配置文件名, profile=dev指定环境配置,即找到 config-client-dev.properties配置文件, 这样一来ConfigServer就可以通过 ConfigServer去到git远程仓库找到对应的配置文件作为自己的配置项。 >5.编写测试用的HelloController ,该类中去读取配置中的 notify,而正好我们的git配置中是有该配置的,我们希望他可以从git中获取配置 ``` @RestController public class HelloController { @Value("${notify}") //从配置中取值 private String notify; @RequestMapping("/hello") public String hello(){ return notify; } } ``` >6.测试:依次启动 ConfigServer,ConfigClient ,在启动ConfigClient时你会发现tomcat端口已经变成了:7777 ,访问 : localhost:7777/hello 你可以看到 “You are successful for dev” , 到这里说明确实从git中取到配置参数。如果把配置:bootstrap.properties中的 spring.cloud.config.profile=test即可完成环境的切换,使用config-client-test.properties作为配置
叩丁狼学员采访 叩丁狼学员采访
叩丁狼头条 叩丁狼头条
叩丁狼在线课程 叩丁狼在线课程