上传文件到GitHub
把之前上传到GitHub的microservice-config库中的文件都删除掉,再新建三个文件:application.yml、crm-dev.yml、crm-test.yml,然后上传到GitHub的microservice-config库中
application.yml内容为:
1 2 3 4 5 6 7 8 9 10 11 12
| spring: profiles: active: - dev --- spring: profiles: dev port: 111 --- spring: profiles: test port: 222
|
crm-dev.yml内容为:
crm-test.yml
使用步骤
新建Module
在idea中新建一个Module,为Maven项目,命名为:microservice-config-client-5001
加入依赖
1 2 3 4 5 6 7 8 9 10 11 12
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
|
application.yml配置
1 2 3
| server: port: 5001 context-path: /
|
bootstrap.yml配置
新建一个配置文件,命名为:bootstrap.yml,优先级比application.yml高
1 2 3 4 5 6 7 8 9 10
| spring: application: name: application-dev cloud: config: name: crm uri: http://configserver.ledao.com:4001 profile: dev label: master fail-fast: true
|
添加启动类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.ledao;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) public class ConfigClientApplication_5001 {
public static void main(String[] args) { SpringApplication.run(ConfigClientApplication_5001.class, args); } }
|
添加ConfigClientController类
主要用于提供测试接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| package com.ledao.controller;
import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
@RestController public class ConfigClientController {
@Value("${port}") private String port;
@RequestMapping("/getPort") public String getPort() { return port; }
public void setPort(String port) { this.port = port; } }
|
添加本地域名映射
找到 C:\Windows\System32\drivers\etc 打开hosts,底部加配置:
1
| 127.0.0.1 client-config.ledao.com
|
测试
地址栏输入:http://client-config.ledao.com:5001/getPort ,根据bootstrap.yml的配置获取不同文件的port
当spring.cloud.config.name=application,spring.cloud.config.profile=dev时
返回111
,此时返回的是application.yml的dev端口
当spring.cloud.config.name=application,spring.cloud.config.profile=test时
返回222
,此时返回的是application.yml的test端口
当spring.cloud.config.name=crm,spring.cloud.config.profile=dev时
返回7777
,此时返回的是crm-dev.yml的端口
当spring.cloud.config.name=crm,spring.cloud.config.profile=test时
返回88888
,此时返回的是crm-test.yml的端口