1. 程式人生 > >Spring Cloud學習筆記(十)-配置中心Config元件從GitHub讀取配置檔案

Spring Cloud學習筆記(十)-配置中心Config元件從GitHub讀取配置檔案

說明:本文僅作為本人學習<<深入理解Spring Cloud與微服務構建>>一書的學習筆記,所有程式碼案例及文字描述均參考該書,不足之處,請留言指正,不勝感激.
一.為什麼要使用Config元件?
  我覺得主要有兩點,方便配置統一管理以及在更改配置時不用重啟服務.
二.搭建Config Server服務
  首先,我們需要了解的是,Config Server既可以通過本地讀取配置檔案,也可以通過遠端倉庫讀取配置檔案,配置稍有不同,這裡只演示從GitHub讀取配置檔案.
  我們先建立一個Module工程,取名config-server,然後在pom檔案中引入Config Server的起步依賴spring-cloud-config-server,以及Eureka Client的起步依賴spring-cloud-starter-eureka,如下:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId
>
</dependency>

  接著,在啟動類上加上@EnableConfigServer,開啟Config Server的功能,如下:

@SpringBootApplication
@EnableEurekaClient
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

  最後,在application.yml中做相關的配置,定義服務名,埠,將服務註冊到Eureka Server,以及Config的配置,如下:

spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/fly-zhyu/spring-cloud.git
          search-paths: project-config
          username: my username
          password: my password
server:
  port: 8787 
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ipAddress}:${server.port}

  綜上,一個Config Server就搭建好了.
三.新建一個目錄來存放配置檔案
  首先看下我們的專案結構:
這裡寫圖片描述
我們新建了一個project-config的目錄來存放我們的配置檔案.
四.修改消費者服務
  首先,我們引入Config Client的起步依賴,如下:

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

  其次,我們將消費者服務的配置檔案移動到project-config中,並調整配置如下:
這裡寫圖片描述
  然後,我們修改消費者服務配置檔案,首先介紹下bootstrap.yml檔案,bootstrap相對於application具有優先執行的順序,Config元件最終是通過config.name-config.profile來匹配對應配置檔案的,如下:
這裡寫圖片描述
  最後我們依次啟動eureka-server,config-server,customer-server,會發現啟動成功,訪問http://localhost:8764/customer/value, 如下:
這裡寫圖片描述
這裡寫圖片描述
說明我們成功的從GitHub上獲取到了配置,這裡我們來梳理一下,我們先建立了一個Config Server,並將它註冊到Eureka Server,並在其中配置好配置檔案在GitHub上的存放路徑,接著我們將配置檔案上傳到GitHub的對應目錄下.當我們啟動customer-server時,伺服器先載入bootstrap檔案,將服務註冊到Eureka,並獲取其他服務的註冊列表,所以我們可以通過service-id: config-server找到配置服務,再通過配置服務連線到GitHub,然後匹配到對應的配置檔案(config.name-config.profile),從而完成整個流程.