代码已上传到Github,有兴趣的同学可以下载来看看:https://github.com/ylw-github/SpringCloud-Eureka-Demo
1. Eureka高可用原理
在微服务中,注册中心非常核心,可以实现服务治理,如果一旦注册出现故障的时候,可能会导致整个微服务无法访问,在这时候就需要对注册中心实现高可用集群模式。
默认情况下Eureka是让服务注册中心,不注册自己。
###因为该应用为注册中心,不会注册自己
register-with-eureka: true
###不需要去注册中心上检索服务
fetch-registry: true
Eureka高可用实际上将自己作为服务向其他服务注册中心注册自己,这样就可以形成一组相互注册的服务注册中心,从而实现服务清单的互相同步,达到高可用效果。
2. Eureka集群搭建
2.1 Eureka01配置
1.application.yml配置:
###服务端口号
server:
port: 8101
###eureka 基本信息配置
spring:
application:
name: eureka-server-01
eureka:
instance:
###注册到eurekaip地址
hostname: 127.0.0.1
client:
serviceUrl:
defaultZone: http://127.0.0.1:8102/eureka/
###因为自己是为注册中心,不需要自己注册自己
register-with-eureka: true
###因为自己是为注册中心,不需要检索服务
fetch-registry: true
2.启动类:
@EnableEurekaServer
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
2.3 Eureka02配置
1.application.yml配置:
###服务端口号
server:
port: 8102
###eureka 基本信息配置
spring:
application:
name: eureka-server-02
eureka:
instance:
###注册到eurekaip地址
hostname: 127.0.0.1
client:
serviceUrl:
defaultZone: http://127.0.0.1:8101/eureka/
###因为自己是为注册中心,不需要自己注册自己
register-with-eureka: true
###因为自己是为注册中心,不需要检索服务
fetch-registry: true
2.启动类:
@EnableEurekaServer
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
2.3 客户端集成Eureka集群
Eureka-ServiceA和Eureka-ServiceB的搭建可以参考上一篇博客《SpringCloud- 服务治理Eureka(搭建注册中心)》,主要修改application.yml。
Eureka-ServiceA:
###服务启动端口号
server:
port: 8000
###服务名称(服务注册到eureka名称)
spring:
application:
name: app-service-a
####服务注册到eureka地址
#eureka:
# client:
# service-url:
# defaultZone: http://localhost:8100/eureka
#
#
# ###因为该应用为注册中心,不会注册自己
# register-with-eureka: true
# ###是否需要从eureka上获取注册信息
# fetch-registry: true
eureka:
client:
service-url:
defaultZone: http://localhost:8101/eureka,http://localhost:8102/eureka
register-with-eureka: true
fetch-registry: true
Eureka-ServiceB:
###服务启动端口号
server:
port: 8001
###服务名称(服务注册到eureka名称)
spring:
application:
name: app-service-b
####服务注册到eureka地址
#eureka:
# client:
# service-url:
# defaultZone: http://localhost:8100/eureka
#
#
# ###因为该应用为注册中心,不会注册自己
# register-with-eureka: true
# ###是否需要从eureka上获取注册信息
# fetch-registry: true
eureka:
client:
service-url:
defaultZone: http://localhost:8101/eureka,http://localhost:8102/eureka
register-with-eureka: true
fetch-registry: true
2.4 启动Eureka服务以及客户端
浏览器输入Eureka01注册中心地址和Eureka02注册中心地址,可以看到都注册上了:
Eureka01:
Eureka02:
客户端B去远程调用客户端A的接口:http://localhost:8001/getorder,可以看到调用成功:
现在把Eureka01关掉,模拟宕机,可以看到现在只剩Eureka02一台注册中心可以跑了。
客户端B再次去远程调用客户端A的接口:http://localhost:8001/getorder,可以看到调用成功: