在 Spring Cloud 应用篇 之 Eureka 初体验 一文中,已经介绍了 Eureka 的基本使用了,但是之前 Eureka 只使用了单节点部署,生产上,不可能只有一个节点,所以我们要实现 Eureka 的高可用,本例就在此前代码的基础上进行修改,只部署两个节点。下面进行修改:
(一)修改配置文件如下,让两个 Eureka 互相向对方注册
-
spring: -
profiles: -
active: instance1 -
application: -
name: eureka-service -
eureka: -
client: -
#由于该应用为注册中心,设置为false,表明不向注册中心注册自己 -
register-with-eureka: false -
server: -
enable-self-preservation: false -
#是否从eureka服务器获取注册信息,这里不需要 -
fetch-registry: false -
logging: -
level: -
com: -
netflix: -
eureka: OFF -
discovery: OFF -
management: -
endpoints: -
web: -
exposure: -
include: '*' -
endpoint: -
health: -
show-details: ALWAYS -
--- -
spring: -
profiles: instance1 -
server: -
port: 8761 -
eureka: -
client: -
service-url: -
defaultZone: http://localhost:8762/eureka/ -
--- -
spring: -
profiles: instance2 -
server: -
port: 8762 -
eureka: -
client: -
service-url: -
defaultZone: http://localhost:8761/eureka/
每次启动一个 Eureka 的实例,需改 spring.profiles.active 的值,还有要去掉 Single instance only 的勾选
(二)修改 spring.profiles.active 的值为 instance1,启动 Eureka
修改 spring.profiles.active 的值为 instance2,启动 Eureka
(三)启动之前写的一个服务 spring-demo-service,它的配置文件如下:
-
server: -
port: 8281 -
eureka: -
client: -
serviceUrl: -
defaultZone: http://localhost:8761/eureka/ -
spring: -
application: -
name: spring-demo-service -
management: -
endpoints: -
web: -
exposure: -
include: '*' -
endpoint: -
health: -
show-details: ALWAYS
可以看到,此服务只注册到了 localhost:8761 的 Eureka
(四)访问 http://localhost:8761/,如下,spring-demo-service 已经注册进来
访问 http://localhost:8762/,如下,发现 spring-demo-service 还注册到了 localhost:8762
从 spring-demo-service 的配置文件我们可以看到,它没有向 localhost:8762 注册,但是此时确实注册到了,主要是因为,两个注册中心 Eureka 相互注册了,所有注册到其中一个 Eureka 的服务实例信息会同步到另一个中。
(五)下面我们停止 localhost:8761 的 Eureka,再次访问 http://localhost:8761/,已经发现不能访问了,然后访问 http://localhost:8762/,发现注册列表中仍然有 spring-demo-service 的服务实例,这样,当其中一个节点的 Eureka 出现异常不可用时,还可以访问其他节点的 Eureka。
下面我们再看另一种情况,重启 spring-demo-service 服务,访问 http://localhost:8762/
这个时候,spring-demo-service 的服务在注册中心就没有了,那这种情况肯定是不行的啊,我们想要的结果是,其中一台注册中心挂掉后,服务还可以注册到其它的注册中心去,那要怎么解决这个问题呢?我们只能让每个服务都注册到每个注册中心去,下面我们修改 spring-demo-service 的配置文件如下:
-
server: -
port: 8281 -
eureka: -
client: -
serviceUrl: -
# 向每个注册中心注册 -
defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/ -
spring: -
application: -
name: spring-demo-service -
management: -
endpoints: -
web: -
exposure: -
include: '*' -
endpoint: -
health: -
show-details: ALWAYS
重启 spring-demo-service 服务,这个时候再访问 http://localhost:8762/,就会发现 spring-demo-service 又注册进来了,图就不贴了。至此,我们就实现了 Eureka 的高可用。生产上可能会部署不只两个节点的 Eureka,可能会有三个或更多,只要让它们两两互相注册即可。