《深入理解Spring Cloud与微服务构建》学习笔记(二十)~配置中心Spring Cloud Config

本例重新创建项目,构建一个空的mavan工程。

一、Config Server 从本地读取配置文件
 新建一个moudle config_server ,pom添加依赖

  1.  
    <dependency>
  2.  
    <groupId>org.springframework.cloud</groupId>
  3.  
    <artifactId>spring-cloud-config-server</artifactId>
  4.  
    </dependency>

 启动类添加 @EnableConfigServer 依赖开启配置服务功能,application.yaml添加配置如下:

  1.  
    server:
  2.  
    port: 9001
  3.  
    spring:
  4.  
    profiles:
  5.  
    active: native #从本地读取配置文件
  6.  
    cloud:
  7.  
    config:
  8.  
    server:
  9.  
    native:
  10.  
    search-locations: classpath:/shared #读取classpath下shared目录下的配置

在resource目录下新建shared目录,shared下新建 config-client-dev.yaml配置文件:

  1.  
    server:
  2.  
    port: 3000
  3.  
    foo: foo-version-v1

继续新建一个modulr config_client ,添加config 客户端依赖,如:

  1.  
    <dependency>
  2.  
    <groupId>org.springframework.cloud</groupId>
  3.  
    <artifactId>spring-cloud-starter-config</artifactId>
  4.  
    </dependency>

 添加配置文件application.yaml:

  1.  
    spring:
  2.  
    application:
  3.  
    name: config-client
  4.  
    cloud:
  5.  
    config:
  6.  
    uri: http://localhost:9001 #读取配置文件的config服务地址
  7.  
    fail-fast: true #读取未成功则快速失败
  8.  
    profiles:
  9.  
    active: dev #读取dev配置文件

启动类添加代码,获取服务端配置的foo属性:

  1.  
    @Value("${foo}")
  2.  
    String foo ;
  3.  
     
  4.  
    @GetMapping("/foo")
  5.  
    public String foo(){
  6.  
    return " 读取的远程服务的配置文件foo:"+foo;
  7.  
    }

 此时编码完成,启动config-server、config-client,然而启动config-client的时候控制台一直报错:

一直访问的是默认的端口,并没有使用我们配置的端口,说明配置文件没有被正常加载。
通过调研发现,config-client中配置文件会首先加载bootstrap.yaml,将配置文件application.yaml 修改为 bootstrap.yaml,重新启动发现正常,在浏览器访问:http://localhost:3000/foo  

会看到浏览器输出我们在服务端配置的信息:

原文地址:https://www.cnblogs.com/bruce1992/p/13902649.html