Spring Cloud 进阶之路 -- 统一配置中心 Config Client 端配置

版权声明:本文为老麻原创文章,未经老麻的博客博主允许不得转载。 https://blog.csdn.net/antma/article/details/81359821

Spring Cloud 统一配置中心 - Config Client 搭建步骤:

1、引入依赖

2、application.yml 改为 bootstrap.yml

3、增加spring.cloud.config 相关配置,去掉已提交到git的配置

4、测试去掉的配置是否能从git 成功拉取

具体如下:

1、引入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-client</artifactId>
</dependency>

2、application.yml 改为 bootstrap.yml

     bootstrap.yml(或bootstrap.properties)在程序引导时执行,应用于更早期的配置信息读取,bootstrap.yml 先于 application.yml 加载,因为把数据库连接信息放入了gitee,如果依旧用 application.yml,启动时会报如下错:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

扫描二维码关注公众号,回复: 3893517 查看本文章

所以需要将application.yml 改为 bootstrap.yml,应用启动时,配置信息首先从 config server 加载,取得数据库配置等信息,这里就是提前要拿到的引导配置,用来加载真正需要的配置信息。

改完后启动,看下日志,看到 :Fetching config from server at : http://localhost:8080/   如下图:

3、增加spring.cloud.config 相关配置,去掉已提交到git的配置

这里主要增加:

  cloud:
    config:
      discovery:
        enabled: true
        # 对应注册到Eureka中的配置中心应用名
        service-id: CONFIG
      profile: dev

 完全配置:

spring:
  application:
    name: order
  cloud:
    config:
      discovery:
        enabled: true
        # 对应注册到Eureka中的配置中心应用名
        service-id: CONFIG
      profile: dev
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8091

 已将数据库配置移到git上。

4、测试去掉的配置是否能从git 成功拉取

程序启动成功说明数据库没有问题,另测试了一下是否能获取到git上的配置,上图分别表示:

(1)、service-id对应配置中心应用名
(2)、通过应用名order拼上profile找到配置文件
(3)、测试是否能获取到env
(4)、访问后得到 dev 测试通过,配置成功

另外注意:Eureka 的配置如果放到git上,又不是默认端口的话,就会有问题,加载不到,是因为客户端需要先Eureka 的地址,再通过 Eureka 里的应用名找到配置中心,然后才能通过配置中心去读取配置,如果Eureka 都没有拿到,何谈CONFIG。

猜你喜欢

转载自blog.csdn.net/antma/article/details/81359821