在分布式系统中, 因为服务数量巨多, 为了方便服务配置文件统一管理, 实时更新, 因此须要分布式配置中心组件.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