一、简介
本文接之前的(六)配置中心(Git 版与动态刷新),继续来说说 Spring Cloud Config 的使用。
先来回顾一下,在前文中我们完成了什么:
- 构建了 config-server,连接到 Git 仓库
- 在 Git 上创建了一个 config-repo 目录,用来存储配置信息
- 构建了 config-client,来获取 Git 中的配置信息
- 在 config-client 中开启了 Refresh,动态刷新配置信息
在本文中,我们继续来看看 Spring Cloud Config 的一些其他能力。
二、高可用问题
传统作法
通常在生产环境,Config Server 与服务注册中心一样,我们也需要将其扩展为高可用的集群。在之前实现的 config-server 基础上来实现高可用非常简单,不需要我们为这些服务端做任何额外的配置,只需要遵守一个配置规则:将所有的 Config Server 都指向同一个 Git 仓库,这样所有的配置内容就通过统一的共享文件系统来维护,而客户端在指定 Config Server 位置时,只要配置 Config Server 外的均衡负载即可,就像如下图所示的结构:
注册为服务
虽然通过服务端负载均衡已经能够实现,但是作为架构内的配置管理,本身其实也是可以看作架构中的一个微服务。所以,另外一种方式更为简单的方法就是把 config-server 也注册为服务,这样所有客户端就能以服务的方式进行访问。通过这种方法,只需要启动多个指向同一 Git 仓库位置的 config-server 就能实现高可用了。
配置过程也非常简单,我们基于配置中心 Git 版本的内容来改造。
三、代码改造
服务端改造
添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
在 application.yml 里新增 Eureka 的配置
eureka:
client:
service-url:
defaultZone: http://localhost:7000/eureka/
这样 Server 端的改造就完成了。先启动 Eureka 注册中心,在启动 Server 端,在浏览器中访问:http://localhost:7000/ 就会看到 Server 端已经注册了到注册中心了。
客户端改造
添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置文件
bootstrap.yml
spring:
cloud:
config:
name: config-client # 对应 {application} 部分
profile: dev # 对应 {profile} 部分
label: master # 对应 {label} 部分,即 Git 的分支。如果配置中心使用的是本地存储,则该参数无用
discovery:
enabled: true
service-id: config-server
eureka:
client:
service-url:
defaultZone: http://localhost:7000/eureka/
主要是去掉了 spring.cloud.config.uri
直接指向 Server 端地址的配置,增加了最后的三个配置:
spring.cloud.config.discovery.enabled
:开启 Config 服务发现支持spring.cloud.config.discovery.serviceId
:指定 Server 端的 name, 也就是 Server 端spring.application.name
的值eureka.client.service-url.defaultZone
:指向配置中心的地址
这三个配置都需要放到 bootstrap.yml
配置文件中。
启动 Client 端,在浏览器中访问:http://localhost:7000/ 就会看到 Server 端和 Client 端都已经注册了到注册中心了。
学习借鉴自https://windmt.com/2018/04/19/spring-cloud-8-config-with-eureka/