6.2:配置中心搭建

一. 搭建配置中心

  1. 準備git倉庫:

    1. https://gitee.com/waitforxy/config_cloud.git

    2. 用戶名:[email protected]

    3. 密碼:xdclass.net123

  2. 新建springboot應用,創建config-server

  3. pom.xml中添加依賴

<dependencies>

    <dependency>

        <groupId>org.springframework.cloud</groupId>

        <artifactId>spring-cloud-config-server</artifactId>

    </dependency>

    <dependency>

        <groupId>org.springframework.cloud</groupId>

        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>

    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-test</artifactId>

        <scope>test</scope>

    </dependency>

</dependencies>

 

  1. 添加application.yml

#服務名稱

spring:

  application:

    name: config-server

  cloud:

    config:

      server:

        git:

          uri: https://gitee.com/waitforxy/config_cloud

          username: [email protected]

          password: xdclass.net123

          timeout: 5

          default-label: master

 

#服務的端口號

server:

  port: 9100

 

#指定註冊中心地址

eureka:

  client:

    serviceUrl:

      defaultZone: http://localhost:8761/eureka/

 

  1. 啓動類添加註解

@SpringBootApplication

@EnableConfigServer

public class ConfigServerApplication {

    public static void main(String[] args) {

        SpringApplication.run(ConfigServerApplication.class, args);

    }

}

 

  1. 訪問方式(一定要注意語法,如果有問題,會出錯)

    1. 例子 http://localhost:9100/product-service.yml

    2. 類型

      1. /{name}-{profiles}.properties

      2. /{name}-{profiles}.yml

      3. /{name}-{profiles}.json

      4. /{label}/{name}-{profiles}.yml

    3. 變量解釋:

      1. name 服務器名稱

      2. profile 環境名稱,開發、測試、生產

      3. lable 倉庫分支、默認master分支

    4. 注意:git放的yml但是後綴更改properties,git會自動轉碼

 


二. 配置客戶端

  1. 添加依賴

<dependency>

    <groupId>org.springframework.cloud</groupId>

    <artifactId>spring-cloud-config-client</artifactId>

</dependency>

 

  1. 修改對應服務的配置文件,把application.yml 改爲 bootstrap.yml

#指定註冊中心地址

eureka:

  client:

    serviceUrl:

      defaultZone: http://localhost:8761/eureka/

 

 

#服務的名稱

spring:

  application:

    name: product-service

  #指定從哪個配置中心讀取

  cloud:

    config:

      discovery:

        service-id: CONFIG-SERVER

        enabled: true

      profile: test

      #建議用lable去區分環境,默認是lable是master分支

      #label: test

 

  1. 注意點:

    1. 配置文件要用bootstrap.yml

    2. 默認讀取文件名是 服務名稱

 


三. 配置中心動態刷新

  1. 在config-clinet的pom.xml中新增spring-boot-starter-actuator監控模塊,其中包含了/refresh刷新API。

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

 

  1. 通過上面的介紹,大家不難想到,該功能還可以同Git倉庫的Web Hook功能進行關聯,當有Git提交變化時,就給對應的配置主機發送/refresh請求來實現配置信息的實時更新。但是,當我們的系統發展壯大之後,維護這樣的刷新清單也將成爲一個非常大的負擔,而且很容易犯錯,那麼有什麼辦法可以解決這個複雜度呢?後續我們將繼續介紹如何通過Spring Cloud Bus來實現以消息總線的方式進行通知配置信息的變化,完成集羣上的自動化更新。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章