1. 程式人生 > >SpringCloud實戰之初級入門(三)— spring cloud config搭建git配置中心

SpringCloud實戰之初級入門(三)— spring cloud config搭建git配置中心

目錄

1.環境介紹

上一篇文章中,我們介紹瞭如何利用eureka註冊中心釋出服務以及呼叫服務,有興趣的小夥伴可以去看看我的前兩篇檔案。
本篇文章我們介紹如何利用spring config sever配合github搭建配置中心,請準備github的賬號一個,或者自建git環境也行。

2.配置中心

2.1 建立工程

和前面一樣,建立一個名為“mirco-service-config”的工程,在pom檔案中加入

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

2.2 修改配置檔案

server:
  port: 7001

spring:
  application:
    name: service-config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/yb2020/spring-cloud-study-example.git
          username: your github username
          password: your github password
          search-paths: mirco-service-config

引數介紹
uri: github對應的repository
username: github的賬號
password: github的密碼
search-paths: 對應repository的配置檔案目錄

2.3 在github中加入配置檔案

在github中加入目錄mirco-service-config,我們將上一個工程“mirco-service-consumer”的配置檔案內容加入一個名為“consumer-test.yml”,並提交。文章中只講這一個改造,視訊中會改造多個工程。

2.3 修改啟動檔案

  1. 在啟動檔案中加上"@EnableConfigServer"註解,然後啟動工程。

  2. 開啟瀏覽器訪問http://localhost:7001/consumer/test,可以看到如下圖內容,說明配置中心已經成功配置完成。
{
    "name": "consumer",
    "profiles": ["test"],
    "label": null,
    "version": "cd27a62ff16b45d1f9aed89fa338cd9671069c19",
    "state": null,
    "propertySources": [{
        "name": "https://github.com/yb2020/spring-cloud-study-example.git/mirco-service-config/consumer-test.yml",
        "source": {
            "server.port": 8002,
            "spring.application.name": "service-consumer",
            "eureka.client.service-url.defaultZone": "http://localhost:9001/eureka/"
        }
    }]
}

3. 訪問配置中心

接下來,其他微服務改造一下,將配置改為從配置中心獲取,我們以"mirco-service-consumer"工程為例。

  • 因為我們已經將配置內容放到名稱"consumer-test.yml"檔案中,將工程中的application.yml檔案刪除或者改字尾為“yml1”,因為applicaiton.yml是springboot啟動時會預設讀取的配置,為了看到效果,我們刪除。

  • 在pom檔案中加入
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
  • 新增“bootstrap.yml”檔案,內容如下:
spring:
  cloud:
    config:
      name: consumer #對應你的配置檔名稱
      uri: http://localhost:7001
      profile: test #對應配置檔案的test、dev、pro
      label: master #對應git的branch
  • 因為我們已經將application.yml刪除了,所以我們新增以下測試程式碼,測試我們是否連線上了配置中心。
@RestController
public class MyFristConfigController {
    
    @Value("${server.port}")
    private String port ;
    
    @RequestMapping(value="/getPort", method=RequestMethod.GET)
    public String getPort() {
        return port ;
    }
}