1、简介
在基于微服务架构下开发,由于服务数量巨多、在高可用性的驱使下要进行集群时,众多节点及服务的配置管理,变得苦不堪言,简直成了体力活,稍微不细心将会出现配置错误。为了方便服务配置信息的统一集中化管理,实时更新,SpringCloud中Spring Cloud Config组件(配置中心),就用来解决这类问题,以达到配置集中化管理,让你可以把配置集中放到远程服务器,集中化管理集群配置。
从配置中心Spring Cloud Config的源码(spring-cloud-config-server)中,可以看出目前配置中心支持本地存储、Git仓库存储、SVN仓库存储、数据库存储方式,其他存储方式可参考源码自行实现即可。
2、配置中心服务端Config Server
配置中心服务端依赖于spring-cloud-config-server包,创建一个普通的springBoot项目springCloudConfig-git(此处以git方式存储为例),额外添加如下依赖包:
<!-- config-server配置中心 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
在启动类ConfigServerGitApplication中添加@EnableConfigServer注解,即:开启支持配置中心的功能,如下:
package com.xcbeyond.springcloud.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* 配置中心。</br>
* 以git方式存储配置
* @author xcbeyond
* 2018年9月17日下午11:44:10
*/
@SpringBootApplication
//开启配置服务器的支持
@EnableConfigServer
//开启作为Eureka Server的客户端的支持
@EnableEurekaClient
public class ConfigServerGitApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerGitApplication.class, args);
}
}
在配置文件application.yml中进行如下配置:
此处为git仓库集中管理配置文件的配置方式。
(本例中配置了注册中心,如果不需要,则可删除注册中心的配置)
#当前配置服务器端口
server:
port: 8888
spring:
application:
name: config-center
cloud:
#配置中心配置
config:
server:
git:
#配置git仓库地址
uri: https://github.com/xcbeyond/springCloudLearning.git
#配置仓库路径
search-paths: config-repo
#配置文件本地临时存储目录
# basedir: target/config
#访问git仓库的用户名.如果Git仓库为公开仓库,可以不填写用户名和密码,如果是私有仓库需要填写
# username: xxx
# password: xxx
#配置仓库的分支
label: master
#Eureka配置
eureka:
client:
serviceUrl:
#服务注册中心地址,需按照注册中心IP进行对应修改
defaultZone: http://register-center:8761/eureka/
instance:
prefer-ip-address: true
配置说明:
spring.cloud.config.server.git.uri 配置git仓库地址
spring.cloud.config.server.git.search-paths 配置仓库路径
spring.cloud.config.server.git.basedir 配置文件本地临时存储目录。一般无需配置。
spring.cloud.config.server.git.username 访问git仓库的用户名.
spring.cloud.config.server.git.password 访问git仓库的密码
spring.cloud.config.label 配置仓库的分支