SpringCloud微服務(06):Config組件,實現配置統一管理

1、Config簡介

在微服務系統中,服務較多,相同的配置:如數據庫信息、緩存、參數等,會出如今不一樣的服務上,若是一個配置發生變化,須要修改不少的服務配置。spring cloud提供配置中心,來解決這個場景問題。
系統中的通用配置存儲在相同的地址:GitHub,Gitee,本地配置服務等,而後配置中心讀取配置以restful發佈出來,其它服務能夠調用接口獲取配置信息。

2、配置服務端

一、項目結構

圖片描述

  • 核心註解:@EnableConfigServer

二、核心依賴

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

三、核心配置文件

這裏注意讀取文件的配置node

  • active :native,讀取本地配置;
  • active :git,讀網絡倉庫配置;
server:
  port: 9001
spring:
  application:
    name: config-server-9001
  profiles:
    # 讀取本地
    # active: native
    # 讀取Git
    active: git
  cloud:
    config:
      server:
        native:
          search-locations: classpath:/config
        git:
          # 讀取的倉庫地址
          uri: https://gitee.com/cicadasmile/spring-cloud-config.git
          # 讀取倉庫指定文件夾下
          search-paths: /cloudbaseconfig
          # 非公開須要的登陸帳號
          username:
          password:
      label: master

四、讀取配置內容

不一樣的環境讀取的結果不一樣。git

info:
  date: 20190814
  author: cicada
  sign: develop
  version: V1.0

3、配置客戶端

一、核心依賴

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

二、核心配置文件

在上面的配置中心,配置讀取Git資源,因此這裏的配置也就是讀取Git資源。github

server:
  port: 8001
spring:
  application:
    name: config-client-8001
  profiles:
    active: dev
  cloud:
    config:
      # 讀取本地配置 ---------------------------
      #uri: http://localhost:9001
      ## 讀取策略:快速失敗
      #fail-fast: true
      ## 讀取的文件名:無後綴
      #name: client-8001
      ## 讀取的配置環境
      #profile: dev  # client-8001-dev.yml
      # ----------------------------------------

      # github上的資源名稱 -----------------------
      name: client-8001
      # 讀取的配置環境
      profile: dev
      label: master
      # 本微服務啓動後,經過配置中心6001服務,獲取GitHub的配置文件
      uri: http://localhost:9001
      # ----------------------------------------

三、測試接口

@RestController
public class ClientController {
    @Value("${info.date}")
    private String date ;
    @Value("${info.author}")
    private String author ;
    @Value("${info.sign}")
    private String sign ;
    @Value("${info.version}")
    private String version ;
    /**
     * 獲取配置信息
     */
    @RequestMapping("/getConfigInfo")
    public String getConfigInfo (){
        return date+"-"+author+"-"+sign+"-"+version ;
    }
}

4、基於Eureka配置

上面的模式,經過服務中心,直接獲取配置。下面把註冊中心Eureka加進來。spring

一、項目結構

啓動順序也是以下:數據庫

node06-eureka-7001
config-server-9001
config-client-8001

二、修改配置項

  • 將config-server-9001添加到註冊中心;
  • 配置config-client-8001讀取註冊中心;

完成後Eureka註冊中心效果圖,啓動順序以下:segmentfault

圖片描述

三、修改客戶端配置

經過註冊中心獲取服務,避免使用URI地址。緩存

圖片描述
通過測試後,正確無誤。restful

  • 提醒:國內若是讀取git的配置,可能常常出去沒法加載的問題,該案例使用的是Gitee的地址。

5、源代碼地址

GitHub地址:知了一笑
https://github.com/cicadasmile/spring-cloud-base
碼雲地址:知了一笑
https://gitee.com/cicadasmile/spring-cloud-base

相關文章
相關標籤/搜索