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

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

一、概述

Spring Boot應(yīng)用的配置文件有多種:

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

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

以上,除了配置中心,其他方式都不能動(dòng)態(tài)去改變配置,并且生效,只有配置中心可以動(dòng)態(tài)修改配置并生效。當(dāng)然,并不是所有配置都能生效的,Spring加載后不再變化的配置,是不可能動(dòng)態(tài)改變的,比如啟動(dòng)參數(shù)、zuul/gateway代理轉(zhuǎn)發(fā)配置.

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

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

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

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

首發(fā)地址:
品茗IT-同步發(fā)布

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

二、建立配置中心

因?yàn)榕渲霉芾碓趃it上,首先要選擇你的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倉(cāng)庫(kù)地址
               uri: https://github.com/ffch/ConfigServerTest.git
               # 訪問git倉(cāng)庫(kù)的用戶名
               username: ffch
               # 訪問git倉(cāng)庫(kù)的用戶密碼 如果Git倉(cāng)庫(kù)為公開倉(cāng)庫(kù),可以不填寫用戶名和密碼,如果是私有倉(cāng)庫(kù)需要填寫
               password: 
               #支持帶{application}和{profile}({label}如果需要)占位符的搜索路徑
               search-paths: '{application}'
         # 配置倉(cāng)庫(kù)的分支,可不配
         label: master

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

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

spring.cloud.config.label 指定分支。默認(rèn)是master;

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

2.3 啟動(dòng)

使用main直接啟動(dòng)即可。

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是不會(huì)自動(dòng)刷新配置的,自動(dòng)刷新需要配置git的webhook,感覺略麻煩,但是我們可以手動(dòng)刷新,手動(dòng)刷新需要使用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>

        <!-- 這個(gè)依賴本來是可以不加的,但是配置沒辦法刷新,加上它可以手動(dòng)刷新配置 -->
        <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文件寫配置,配置文件分為兩個(gè),bootstrap.yml和application.yml:

  • bootstrap.yml的優(yōu)先級(jí)高于application.yml。

  • 配置中心的相關(guān)配置必須放在bootstrap.yml中,否則無(wú)效。

bootstrap.yml:

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

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

spring.application.name是標(biāo)識(shí)了應(yīng)用名。

spring.profiles.active 是激活的環(huán)境,這個(gè)指的是你本地的環(huán)境相關(guān)的配置文件。

spring.cloud.config.uri是配置中心的地址,默認(rèn)是http://localhost:8888。

spring.cloud.config.profile配置中心對(duì)應(yīng)的環(huán)境,可以和spring.profiles.active相同,也可以不同,從配置中心拿配置以該屬性為準(zhǔn)。

spring.cloud.config.label是git倉(cāng)庫(kù)分支,默認(rèn)master

application.yml:


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

application-loc.yml:

env: loc

loc:
   value: hasadasdasdasdad

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

遠(yuǎn)程配置文件:

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

在這里插入圖片描述

3.3 啟動(dòng)

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屬性注入即可。如果要手動(dòng)刷新,記得加上@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 測(cè)試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 注意事項(xiàng)

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

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

config-server地址不寫或yml格式寫錯(cuò),默認(rèn)都是http://localhost:8888

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

3.7 使用到的實(shí)體

ResultModel:


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

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

快速構(gòu)建項(xiàng)目

Spring項(xiàng)目快速開發(fā)工具:

一鍵快速構(gòu)建Spring項(xiàng)目工具

一鍵快速構(gòu)建SpringBoot項(xiàng)目工具

一鍵快速構(gòu)建SpringCloud項(xiàng)目工具

一站式Springboot項(xiàng)目生成

Mysql一鍵生成Mybatis注解Mapper

Spring組件化構(gòu)建

SpringBoot組件化構(gòu)建

SpringCloud服務(wù)化構(gòu)建

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


品茗IT交流群
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容