Spring Cloud (十七)、在微服务中获取配置中心的配置——客户端配置映射

确保已经搭建好了配置中心,可参考:Spring Cloud(十六)、通过Spring Cloud Config构建配置中心

接下来根据以下步骤来进行客户端配置映射,如下:

一、创建一个Spring Boot 工程,命名为config-client。

二、编写pom.xml,内容如下:



   4.0.0
   
      org.springframework.boot
      spring-boot-starter-parent
      2.1.6.RELEASE
       
   
   com.example
   config-client
   0.0.1-SNAPSHOT
   config-client
   Demo project for Spring Boot

   
      1.8
      Greenwich.SR1
   

   
      
         org.springframework.boot
         spring-boot-starter-web
      
      
         org.springframework.cloud
         spring-cloud-starter-config
      

      
         org.springframework.boot
         spring-boot-starter-test
         test
      
   

   
      
         
            org.springframework.cloud
            spring-cloud-dependencies
            ${spring-cloud.version}
            pom
            import
         
      
   

   
      
         
            org.springframework.boot
            spring-boot-maven-plugin
         
      
   

三、创建bootstrap.properties配置文件,内容如下:

Spring Cloud (十七)、在微服务中获取配置中心的配置——客户端配置映射_第1张图片

#对应配置文件规则中的{application}部分
spring.application.name=hdnspace
#对应配置文件规则中的{propfile}部分
spring.cloud.config.profile=dev
#对应配置文件规则中的{label}部分
spring.cloud.config.label=master
#配置中心config-server的地址
spring.cloud.config.uri=http://localhost:7001/

server.port=7002

       必须配置在bootstrap.properties中,这样config-server中的配置信息才能被正确加载。

四、创建一个RESTful接口来返回配置中心的from属性,通过Environment对象来获取配置属性,如:

@RefreshScope
@RestController
public class TestController {
    @Autowired
    private Environment environment;

    @RequestMapping("/from")
    public String from(){
        return environment.getProperty("from");
    }
}

五、测试验证

      启动注册中心eureka-server、配置中心config-server、路径匹配规则中的微服务应用、当前的config-client,访问http://localhost:7002/from,就可以获取到我们配置的den环境的from内容了,如下:

Spring Cloud (十七)、在微服务中获取配置中心的配置——客户端配置映射_第2张图片

 

你可能感兴趣的:(Spring,Cloud)