虽然通过服务端负载均衡已经能够实现,但是作为架构内的配置管理,本身其实也是可以看作架构中的一个微服务。所以,另外一种方式更为简单的方法就是把 config-server 也注册为服务,这样所有客户端就能以服务的方式进行访问。通过这种方法,只需要启动多个指向同一 Git 仓库位置的 config-server 就能实现高可用了。
配置过程也非常简单,我们基于配置中心 Git 版本的内容来改造。
代码改造
服务端改造
添加依赖
在 pom.xml 里边添加以下依赖
<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
profile: dev
label: master
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 的配置中。
欢迎大家加我qq:1038774626探讨技术问题
启动 Client 端,在浏览器中访问:http://localhost:7000/ 就会看到 Server 端和 Client 端都已经注册了到注册中心了。
高可用
为了模拟生产集群环境,我们启动两个 Server 端,端口分别为 12000 和 12001,提供高可用的 Server 端支持。
打包
./mvnw clean package -Dmaven.test.skip=true
启动两个 Server
java -jar target/spring-cloud-config-server-0.0.1-SNAPSHOT.jar --server.port=12000
java -jar target/spring-cloud-config-server-0.0.1-SNAPSHOT.jar --server.port=12001
如上图就可发现会有两个 Server 端同时提供配置中心的服务,防止某一台 down 掉之后影响整个系统的使用。
我们先单独测试服务端,分别访问:http://localhost:12000/config-client/dev 和 http://localhost:12001/config-client/dev 返回信息:
{
"name": "config-client",
"profiles": ["dev"],
"label": null,
"version": "90dd76966da0eed967a0cbce3320f0f7ff63eb6b",
"state": null,
"propertySources": [
{
"name": "https://github.com/zhaoyibo/spring-cloud-study/config-repo/config-client-dev.yml",
"source": {
"info.profile": "dev update"
}
}
]
}
说明两个 Server 端都正常读取到了配置信息。
再次访问 http://localhost:13000/info 返回 dev update。说明客户端已经读取到了 Server 端的内容,我们随机停掉一台 Server 端的服务,再次访问 http://localhost:13000/info 依然返回 dev update,说明达到了高可用的目的。