在分佈式系統中, 因爲服務數量巨多, 爲了方便服務配置文件統一管理, 實時更新, 因此須要分佈式配置中心組件.java
在 spring cloud 中, 有分佈式配置中心組件spring cloud config, 它支持 配置文件 放在 配置服務 的本地內存中, 也支持放在遠程Git倉庫中.git
在 spring cloud config 組件中, 分兩個角色, 一是 config-server , 二是 config-client .spring
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.gy.cloud</groupId> <artifactId>cloud</artifactId> <version>1.0-SNAPSHOT</version> </parent> <artifactId>cloud-f</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>${project.artifactId}</name> <description>Demo project for Spring Cloud Config</description> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> <!-- 配置中心也可加入子服務,進入註冊中心註冊 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies> </project>
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ server: port: 8766 spring: application: name: config-server # Git 倉庫配置 cloud: config: # Git 代碼分支 label: master server: git: # Git 倉庫地址 uri: https://gitee.com/ge.yang/SpringBoot/ # 配置文件存放目錄 search-paths: src/main/resources/config # Git 倉庫帳號密碼 username: password:
@EnableConfigServer 證實此服務是配置中心apache
package com.gy.cloud.cloudf; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.config.server.EnableConfigServer; @EnableConfigServer @EnableDiscoveryClient @SpringBootApplication public class CloudFApplication { public static void main(String[] args) { SpringApplication.run(CloudFApplication.class, args); System.out.println("=== 配置服務F啓動成功 ==="); } }
配置文件信息: app
訪問 : http://localhost:8766/testUsername/devmaven
{"name":"testUsername","profiles":["dev"],"label":null,"version":"f2f23650522db4787e8a2a7d3b030058a8598899","state":null,"propertySources":[]}
訪問 : http://localhost:8766/config-client-dev.properties分佈式
testPassword: Hello World testUsername: 123456789
證實 配置中心 搭建成功 !學習
注意 application.yml 中 Git倉庫配置 的 地址 與 路徑spa
學習文檔
方誌朋的博客 : https://www.fangzhipeng.com/springcloud/2018/08/30/sc-f6-config/code
項目源碼: https://gitee.com/ge.yang/spring-demo/tree/master/cloud