Spring Cloud Config構建分佈式配置中心

 一、 Spring cloud config 介紹

        Spring cloud config是一個分佈式的配置中心,用來給服務端和客戶端實現外部的配置支持。可以充當爲一個配置服務器來使用,爲各應用提供一箇中心化的外部配置。它實現了對服務端和客戶端對Spring Environment和PropertySource的抽象映射,所以它適用於Spring構建的應用程序,也可以在任何其他語言構建的應用程序中使用。

        配置服務器默認採用git來存儲配置信息,可以通過git來對配置進行版本的管理。

 

二、構建一個Spring cloud config應用

     第一種方式: 

       將config-server註冊爲一個服務,然後其他服務直接連接該config-server。步驟如下:

     1. 添加依賴:

       <dependency>                                                

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

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

    </dependency>

        2.  在config-server啓動類上添加一個@EnableConfigServer註解,用來開啓Spring cloud config 。

package com.itmuch.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

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

 

        3. 在配置文件.properties中,添加如下配置:

server:
  port: 8080
spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/zzb15997937197/spring-cloud-config.git/
          username:  git用戶名
          password:  git 密碼
          

        url可以去掉.git以後的內容,只需要加一個倉庫名就行:

          https://github.com/zzb15997937197/spring-cloud-config

 

        4.  在訪問配置前,需要知道url與配置文件的映射關係如下:

        /{application}/{profile}[/{label}]

        /{application}-{profile}.yml /{label}

         /{application}-{profile}.yml

         /{application}-{profile}.properties /{label}

          /{application}-{profile}.properties

 

   5. 在git中新建不同環境的配置文件

         application.properties

         application-dev.properties

         application-test.properties

         application-prod.properties

         然後在每個環境的配置文件中,新增一個from屬性:

          from=git-default-1.0

          from=git-dev-1.0

          from=git-test-1.0

          from=git-prod-1.0

 

  驗證一:  使用瀏覽器直接訪問git配置

    方式一: config-servier啓動成功後可以直接訪問地址:   http://localhost:8080/application-dev.properties,  application-uat.properties爲git中存儲的配置文件名稱。

    返回結果:   profile: dev ,表示拿到了在git倉庫中的  application-dev.properties文件裏的配置:

  方式二:   使用/{application}/{profile}來訪問,查看結果,比如我訪問git上配置爲application-uat.properties的配置文件,只需要

   http://localhost:8080/application/uat

返回結果如下:

解析一下:

{
    "name": "application",
    "profiles": ["uat"],
    "label": "master",
    "version": "d3f880cfcf2fbe2e5ae0beabcce17d8ebc34b4cc",
    "state": null,
    "propertySources": [{
        "name": "https://github.com/zzb15997937197/spring-cloud-config.git/application-uat.properties",
        "source": {
            "profile": "abc"
        }
    }]
}

返回的json裏面包含了,應用名,環境名,版本號,數據源等信息。

若需要禁用引導過程,那麼設置 spring.cloud.bootstrap.enabled=false

 

 


    驗證二: 使用config-client拿到config-server在git中存儲的配置

    1. 啓動一個config-client客戶端,新增一個Bootstrap.yml文件,在bootstrap.yml中添加如下配置:

 添加依賴:

	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
	</dependencies>

 

 

     通過profile來指定配置文件,bootstrap.yml文件中配置屬性如下:

spring:
  cloud:
    config:
      uri: http://localhost:8080
      profile: dev
      label: master   # 當configserver的後端存儲是Git時,默認就是master 
  application:
    name:  config-client

需要注意的是: 以上的屬性配置需要放到bootstrap.yml文件中,不能放到application.yml中。如果是配置到application.yml文件中,spring cloud config client的會連接到spring.cloud.config.uri的默認值http://localhost:8888,而並非配置是http://localhost:8080 地址。

       因爲Spring Cloud有一個"引導上下文" 的概念,這是主應用程序的父上下文。引導上下文負責 從配置服務器加載配置屬性,以及解密外部配置文件中的屬性。和主應用程序加載application.*中的屬性不同,引導上下文加載bootstrap.*中的屬性,該配置屬性的優先級高於application.*,因此默認情況下,不會被本地配置所覆蓋。

 

  2.然後寫一個測試的controller:

package com.itmuch.cloud;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConfigClientController {

  @Value("${profile}")
  private String profile;

  @GetMapping("/profile")
  public String getProfile() {
    return this.profile;
  }


}

訪問:  localhost:8081/profile,結果如下:

 

最後將git中指定profile爲dev的文件中的配置屬性profile取出來了。


 

三、在config-server啓動時加載配置文件

        spring cloud config會在應用獲取到首次請求時,將git上的配置克隆到本地,然後再響應給請求。這樣會導致請求效率很慢的問題,spring cloud config同時也提供了一個配置屬性,用於在服務啓動的時候將git的配置克隆到本地,然後請求過來的時候會快速響應出去, 在bootstrap.yml文件中添加配置:

spring:
  cloud:
    config:
      server:
        git:
          clone-on-start: true

        添加這個配置後,再次用客戶端請求config-server獲取的速度會明顯增加,只不過服務在啓動時的時間會加長點。可以設置日誌的級別爲DEBUG,來看項目啓動時的信息:

logging:
  level:
    org:
      springframework:
        cloud: DEBUG
        boot: DEBUG

信息:

可以從控制檯上發現,Spring Cloud Config已經將git的配置克隆到本地一個文件中:

2020-06-14 14:59:34.635  INFO 22840 --- [nio-8080-exec-1] o.s.c.c.s.e.NativeEnvironmentRepository  : Adding property source: file:/C:/Users/ADMINI~1/AppData/Local/Temp/config-repo-2472557199743150060/application-dev.properties
 

訪問的時候的日誌:

2020-06-14 20:48:35.272 DEBUG 55968 --- [nio-8080-exec-1] s.b.e.YamlPropertySourceLoader$Processor : Unmatched document: {server={port=8080}, spring={cloud={config={server={git={uri=https://github.com/zzb15997937197/spring-cloud-config, username=***, password=***., clone-on-start=true, search-paths=[foo, bar]}}}}}, logging={level={org.springframework.cloud=DEBUG, org.springframework.boot=DEBUG}}}

 


 

 

     

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