天天看點

SpringCloud Config 公共配置檔案的使用

前言:

在SpringCloud中,我們一般會是SpringCloud Config作為配置中心,管理所有服務的配置資訊,友善配置資訊的管理與維護。但是随着微服務的逐漸增多,你會發現每一個服務都會有相同的配置檔案。如果不對它們進行整合,勢必會對配置資訊的維護帶了一定的煩惱。是以,我們這裡将介紹一種配置公共檔案的方法,具體如下文。

正文:

這種方法實作起來非常簡單,我需要在Config配置中心的目錄下,建立common-[profile_name].yml(例如:common-dev.yml),可以在該檔案下配置一些公用配置資訊,例如:

#公用配置
##-----------------------Spring配置---------------------
spring:
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss
  ###-----------------------Sleuth分布式跟蹤配置---------------------
  sleuth:
    sampler:
      percentage: 1.0 #指定需要采樣的請求的百分比,預設值是0.1(10%)。
  ###-----------------------Zipkin鍊路追蹤配置---------------------
  zipkin:
    base-url: http://hanxiaozhang-zipkin-server/
  ###-----------------------Springboot admin 配置---------------------
  boot:
    admin:
      client:
        url:  http://localhost:8018
        username: user
        password: user

##-----------------------actuator健康檢查配置---------------------
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always
           

 然後在每一個微服務的bootstrap.yml中配置如下資訊,就可以實作公共配置檔案的取讀了。

spring:
  application:
    name: hanxiaozhang-user-oauth2
  cloud:
    config:
      fail-fast: true  # 擷取不到遠端配置時,立即失敗
      name: ${spring.application.name},common  # 配置公用的common
      profile: ${spring.profiles.active}
      label: master
      discovery:
        enabled: true
        service-id: hanxiaozhang-config
           

控制台輸出日志如下:

2020-10-28 18:49:20.009  INFO [hanxiaozhang-zuul,,,] 37188 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Located environment: name=hanxiaozhang-zuul,common, profiles=[dev], label=master, version=5677f5faedcf827c4fe302a4885a165c52427c47, state=null
2020-10-28 18:49:20.010  INFO [hanxiaozhang-zuul,,,] 37188 --- [           main] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='configService', propertySources=[MapPropertySource {name='configClient'}, MapPropertySource {name='https://gitee.com/hanxinghua2017/hanxiaozhang//config-repo/common-dev.yml'}, MapPropertySource {name='https://gitee.com/hanxinghua2017/hanxiaozhang//config-repo/hanxiaozhang-zuul-dev.yml'}]}