SpringCloud技術指南系列(十)配置管理之自建配置中心(spring-cloud-config-server的使用)

SpringCloud技術指南系列(十)配置管理之自建配置中心(spring-cloud-config-server的使用)

一、概述

Spring Boot應用的配置文件有多種:

  1. 我們可以將配置內容寫入application.yml
  2. 設置多個profile,也可以用多個application-{profile}.properties文件配置
  3. 命令行參數
  4. 自定義配置文件
  5. 配置中心

詳細可以查看《SpringBoot入門建站全系列(二十三)配置文件優先級及常用配置方式》.

以上,除了配置中心,其他方式都不能動態去改變配置,并且生效,只有配置中心可以動態修改配置并生效。當然,并不是所有配置都能生效的,Spring加載后不再變化的配置,是不可能動態改變的,比如啟動參數、zuul/gateway代理轉發配置.

《SpringCloud技術指南系列(八)配置管理之Consul配置中心》,講述了如何使用consul做配置中心對配置進行管理。

《SpringCloud技術指南系列(九)配置管理之Zookeeper配置中心》,講述了如何使用zookeeper做配置中心。

本篇講述如何自建配置中心,以GitHub為配置管理中心,使用spring-cloud-config-server建立配置中心。

代碼可以在SpringBoot組件化構建https://www.pomit.cn/java/spring/springcloud.html中的IConfigServer和IconfigClient組件中查看,并下載。

首發地址:
品茗IT-同步發布

如果大家正在尋找一個java的學習環境,或者在開發中遇到困難,可以<a
href="https://jq.qq.com/?_wv=1027&k=52sgH1J"
target="_blank">
加入我們的java學習圈,點擊即可加入
</a>
,共同學習,節約學習時間,減少很多在學習中遇到的難題。

二、建立配置中心

因為配置管理在git上,首先要選擇你的git,我選擇的是github.

2.1 引入依賴

需要引入spring-boot-starter-web和spring-cloud-config-server.

依賴如下:

<?xml version="1.0"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.pomit</groupId>
        <artifactId>springcloudwork</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>IConfigServer</artifactId>
    <name>IConfigServer</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven-jar-plugin.version>2.6</maven-jar-plugin.version>
    </properties>

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

父模塊pom文件可以在https://www.pomit.cn/spring/SpringCloudWork/pom.xml獲取。

2.2 配置文件

這里使用yaml文件寫配置,配置文件application.yml:

application.yml:

server:
   port: 8888
spring:
   application:
      name: ConfigServer
   cloud:
      config:
         server:
            git:
               # 配置git倉庫地址
               uri: https://github.com/ffch/ConfigServerTest.git
               # 訪問git倉庫的用戶名
               username: ffch
               # 訪問git倉庫的用戶密碼 如果Git倉庫為公開倉庫,可以不填寫用戶名和密碼,如果是私有倉庫需要填寫
               password: 
               #支持帶{application}和{profile}({label}如果需要)占位符的搜索路徑
               search-paths: '{application}'
         # 配置倉庫的分支,可不配
         label: master

這里,表示配置中心建立在8888端口,名字是ConfigServer。

另外,需要配置git地址、用戶名、密碼;

spring.cloud.config.label 指定分支。默認是master;

spring.cloud.config.server.search-paths是尋找配置文件的路徑,{application}表示uri下的對應的應用名稱(客戶端)下找配置文件。{profile}表示uri下的對應的環境(客戶端)下找配置文件。

2.3 啟動

使用main直接啟動即可。

ConfigServerApplication:

package cn.pomit.springbootwork.config.server;

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

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

2.4 映射查詢

配置中心將github上的配置文件以下面這些格式也映射。

如,映射{application}-{profile}.properties文件:

/{application}/{profile}/[{label}]
/{label}/{application}-{profile}.properties
/{application}-{profile}.properties
/{label}/{application}-{profile}.yml
/{application}-{profile}.yml

如:訪問http://127.0.0.1:8888/ConfigClient/dev,返回

{"name":"ConfigClient","profiles":["dev"],"label":null,"version":"8d6f304f47055752be51e35ec74aceb40ea0c26d","state":null,"propertySources":[{"name":"https://github.com/ffch/ConfigServerTest.git/ConfigClient/ConfigClient-dev.properties","source":{"git.value":"456asdasdada"}}]}

它查找的是配置的github地址下的ConfigClient目錄下的ConfigClient-dev.properties文件(我的配置)。

三、客戶端使用配置中心

3.1 引入依賴

需要引入spring-boot-starter-web和spring-cloud-starter-config.

spring-cloud-config-server是不會自動刷新配置的,自動刷新需要配置git的webhook,感覺略麻煩,但是我們可以手動刷新,手動刷新需要使用spring-boot-starter-actuator

依賴如下:

<?xml version="1.0"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.pomit</groupId>
        <artifactId>springcloudwork</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>IConfigClient</artifactId>
    <name>IConfigClient</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven-jar-plugin.version>2.6</maven-jar-plugin.version>
    </properties>

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

        <!-- 這個依賴本來是可以不加的,但是配置沒辦法刷新,加上它可以手動刷新配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>
</project>

父模塊pom文件可以在https://www.pomit.cn/spring/SpringCloudWork/pom.xml獲取。

3.2 配置文件

這里使用yaml文件寫配置,配置文件分為兩個,bootstrap.yml和application.yml:

  • bootstrap.yml的優先級高于application.yml。

  • 配置中心的相關配置必須放在bootstrap.yml中,否則無效。

bootstrap.yml:

server:
   port: 8814
spring:
   application:
      name: ConfigClient
   profiles:
      active: loc
   cloud:
      config:
         uri: http://localhost:8888 # 對應config-server地址,默認值http://localhost:8888
         profile: dev # 對應ConfigServer獲取的配置文件的{profile}
         label: master # 對應ConfigServer獲取的配置文件的{label},即Git倉庫分支支
#手動刷新配使用
management:
  endpoints:
    web:
      exposure:
        #加載所有的端點,默認只加載了info、health
        include: '*'

這里面,包含了端口、應用名、配置中心信息。

spring.application.name是標識了應用名。

spring.profiles.active 是激活的環境,這個指的是你本地的環境相關的配置文件。

spring.cloud.config.uri是配置中心的地址,默認是http://localhost:8888

spring.cloud.config.profile配置中心對應的環境,可以和spring.profiles.active相同,也可以不同,從配置中心拿配置以該屬性為準。

spring.cloud.config.label是git倉庫分支,默認master

application.yml:


application.yml中仍可以配置一些常用配置,我這里啥都沒寫。

application-loc.yml:

env: loc

loc:
   value: hasadasdasdasdad

application-loc.yml中我配置了一個loc.value的值。

遠程配置文件:

如下圖所示,我在GitHub上只配置了git.value一個屬性:

在這里插入圖片描述

3.3 啟動

ConfigClientApplication :

package cn.pomit.springbootwork.config.client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

3.4 屬性注入

直接使用@Value屬性注入即可。如果要手動刷新,記得加上@RefreshScope注解。

ConfigInfoService :

package cn.pomit.springbootwork.config.client.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

@RefreshScope
@Service
public class ConfigInfoService {
    @Value("${git.value}")
    private String gitValue;
    @Value("${loc.value}")
    private String locValue;

    public String locValue() {
        System.out.println(locValue);
        return locValue;
    }

    public String gitValue() {
        System.out.println(gitValue);
        return gitValue;
    }

}

3.5 測試web

ConsulConfigRest:

package cn.pomit.springbootwork.config.client.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.pomit.springbootwork.config.client.model.ResultModel;
import cn.pomit.springbootwork.config.client.service.ConfigInfoService;

@RestController
@RequestMapping("/configTest")
public class ConsulConfigRest {
    @Autowired
    ConfigInfoService configInfoService;

    @RequestMapping(value = "/locValue", method = { RequestMethod.GET })
    public ResultModel locValue() {
        return ResultModel.ok(configInfoService.locValue());
    }
    
    @RequestMapping(value = "/gitValue", method = { RequestMethod.GET })
    public ResultModel gitValue() {
        return ResultModel.ok(configInfoService.gitValue());
    }
}

3.6 注意事項

客戶端讀取遠程配置依賴的配置是spring.cloud.profile,而不是spring.profiles.active;

本地配置仍是按照spring.profiles.active讀??;

config-server地址不寫或yml格式寫錯,默認都是http://localhost:8888

不會自動刷新,使用spring-boot-starter-actuator并配置后,可以手動刷新。http://127.0.0.1:8814/actuator/refresh (不同的actuator版本略有不同)

3.7 使用到的實體

ResultModel:


詳細完整的實體,可以訪問品茗IT-博客《SpringCloud技術指南系列(十)配置管理之自建配置中心(spring-cloud-config-server的使用)》進行查看

品茗IT-博客專題:https://www.pomit.cn/lecture.html匯總了Spring專題Springboot專題、SpringCloud專題、web基礎配置專題。

快速構建項目

Spring項目快速開發工具:

一鍵快速構建Spring項目工具

一鍵快速構建SpringBoot項目工具

一鍵快速構建SpringCloud項目工具

一站式Springboot項目生成

Mysql一鍵生成Mybatis注解Mapper

Spring組件化構建

SpringBoot組件化構建

SpringCloud服務化構建

喜歡這篇文章么,喜歡就加入我們一起討論SpringBoot使用吧!


品茗IT交流群
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容