跳到主要内容

3. Spring Cloud Eureka 实现高可用服务发现注册中心

前两篇实现了单点注册中心的实现,并实现了一个服务提供者和一个消费者,之后在基础上有增加了安全控制。

本篇来实现一个高可用版的服务注册中心。在线上环境中,使用高可用是最基本的要求,如果有单点故障的时候,不至于整个服务都无响应。

这里的高可用包括注册中心的高可用,服务提供者注册到服务中心集群上,这样服务消费者发现服务的时候就通过集群来实现,不会出现注册中心不可用,造成整个系统崩溃。

还包括服务提供者的高可用,一个服务提供者注册多个实例到注册中心,这样,即时有其中某个实例 down 掉,其他实例依然可以提供服务。

高可用服务注册发现中心

下图是 Eureka 官方提供的高可用架构图。

eureka_architecture

1、创建注册中心,重点在于配置文件

bootstrap.yml 配置如下:

spring:
application:
name: eureka-ha-center ## 设置应用的名称
cloud:
inetutils:
ignoredInterfaces:
- docker0
- veth.*
- VM.*
preferredNetworks:
- 192.168

application.yml 配置如下:

spring:
profiles: eureka-center1
server:
port: 1989
eureka:
instance:
hostname: ha-eureak-center1
appname: 注册中心
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://localhost:1988/eureka ## 注册到 eureka-center2 上,端口1988


---
spring:
profiles: eureka-center2
server:
port: 1988
eureka:
instance:
hostname: ha-eureak-center2
appname: 注册中心
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://localhost:1989/eureka ## 注册到 eureka-center1 上,端口1989

通过 profiles 参数,稍后在启动的时候根据 vm 参数决定启用配置。

client.registerWithEureka 和 client.registerWithEureka 设置为 true,表示要注册到 eureka 。单点模式中设置为 false。高可用版本要允许注册到 eureka 。注意:eureka-center1 和 eureka-center2 的 serviceUrl.defaultZone 是互相注册的。

2、启动应用。

  • 通过设置 vm 参数 -Dspring.profiles.active=eureka-center1 在 1989 端口启动注册中心1

  • 通过设置 vm 参数 -Dspring.profiles.active=eureka-center2 在 1988 端口启动注册中心2。

之后访问 http://localhost:1988http://localhost:1989 都能进入 eureka ui 界面,并且能看到注册到自身的eureka 服务。

eureka-ha-center

2、创建高可用的服务提供者,并注册到上面的两个注册中心

application.yml 配置如下:

spring:
profiles: ha-provider1
application:
name: ha-provider
security:
user:
name: root
password: root
server:
port: 1990
eureka:
instance:
preferIpAddress: true
client:
serviceUrl:
defaultZone: http://localhost:1989/eureka,http://localhost:1988/eureka


---
spring:
profiles: ha-provider2
application:
name: ha-provider
security:
user:
name: root
password: root
server:
port: 1991
eureka:
instance:
preferIpAddress: true
client:
serviceUrl:
defaultZone: http://localhost:1989/eureka,http://localhost:1988/eureka

同样利用 profiles 区分两个服务提供者。

注意,defaultZone 设置了上面启动的两个注册中心服务,中间用逗号隔开。

之后设置 vm 参数 -Dspring.profiles.active=ha-provider1 启动第一个服务提供者,设置 vm 参数 -Dspring.profiles.active=ha-provider2 启动第二个服务提供者。

之后打开 eureka ui 界面,看到已经注册到注册中心

eurea-ha-provider

3、创建服务消费者

application.yml 配置:

spring:
application:
name: ha-customer
server:
port: 1992
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1989/eureka,http://localhost:1988/eureka
instance:
preferIpAddress: true

启动服务消费者

通过访问 http 接口,查看服务是否可用,通过日志可以看出每次调用有可能负载到不同的服务提供者实例上。

4、停掉一个服务提供者。

eureka-ha-provider-down

访问 http 接口,不影响服务,会自动负载到正常的服务提供者实例上。

5、停掉一个注册中心实例。

eureka-ha-center-down

访问 http 接口,仍然不受影响。