SpringCloud快速上手|分布式配置中心及其高可用

简介

在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件。在Spring Cloud中,有分布式配置中心组件spring cloud config ,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程Git仓库中。在spring cloud config 组件中,分两个角色,一是config server,二是config client。

向git中传入配置文件组

文件名分别为

segmentfault-dev.properties
segmentfault-production.properties
segmentfault-test.properties

对应三个不同的环境
该文件的命名规则是:{application}-{profile}.properties

Config Server
//启动类
@SpringBootApplication
@EnableConfigServer //关键
public class ConfigServerApplication {

	public static void main(String[] args) {
		SpringApplication.run(ConfigServerApplication.class, args);
	}
}
spring.application.name=config-server
server.port=8888

spring.cloud.config.server.git.uri=https://github.com/forezp/SpringcloudConfig/
spring.cloud.config.server.git.searchPaths=respo
spring.cloud.config.label=master
spring.cloud.config.server.git.username=your username
spring.cloud.config.server.git.password=your password
//公开仓库不用填写账号密码

这时我们启动该服务,访问该配置文件,访问路径示例如下(以该配置为例):
127.0.0.1:8888/segmentfault-dev.properties
访问路径的写法也有多种方式:

/{application}/{profile}/[label]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
其中{label}是指分支,默认是master。

Config Client

bootstrap.properties

//配置以spring.cloud.config开头的配置
#配置服务实例名称,即哪个应用要使用这个配置
#可以不写,若没写则使用application.properties中的spring.application.name值,即当前应用名称
spring.cloud.config.name=segmentfault
#配置文件所在分支
spring.cloud.config.label=master
spring.cloud.config.profile=prod
#配置配置服务器地址
spring.cloud.config.uri=http://localhost:8091/

application.properties

#bootstrap.properties中未配置spring.cloud.config.name则使用这个值
spring.application.name=segmentfault
server.port=8765

这样配置客户端可以接收到git中的配置项了

高可用集群:

改造配置服务端:

//配置新增:
#注册到Eureka
eureka.client.serviceUrl.defaultZone=http://localhost:8889/eureka/
//启动类新增
@EnableEurekaServer

改造配置客户端:

//bootstrap.properties
spring.cloud.config.name=segmentfault
spring.cloud.config.label=master
spring.cloud.config.profile=prod
#不再使用ip地址访问配置服务器
//spring.cloud.config.uri=http://localhost:8091/
eureka.client.serviceUrl.defaultZone=http://localhost:8889/eureka/
spring.cloud.config.discovery.enabled=true //启用高可用配置中心
spring.cloud.config.discovery.serviceId=config-server //从配置中心通过配置服务器名寻址
//启动类新增
@EnableEurekaClient
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值