springcloud进阶之eureka集群配置,实现高可用

eureka server 集群
    高可用注册中心   Eureka server 的设计一开始就是考虑了高可用的问题,在eureka 的服务治理设计中,所有节点即是服务提供方,也是消费方,服务注册中心也不列外,单节点的配置中,设置两个参数,让服务注册中心不注册自己

eureka.client.register-with-eureka =false
eureka.client.fetch-registry = false

       Eureka server的高可用实际上就是将自己作为服务向其他服务注册中心注册自己,这样就可以形成一组互相注册的服务注册中心,以实现服务清单的相互同步,达到高可用的效果。
    下面构建一个双节点的服务注册中心集群。
    1.创建application-peer1.yml作为peer1服务中心配置,并将serviceUrl指向peer2

spring:
  application:
    name: eureka-server

server:
  port: 1111

eureka:
  instance:
    hostname: peer1
  client:
    serviceUrl:
      defaultZone: http://localhost:1112/eureka/

2.创建application-peer2.yml作为peer2服务中心的配置,并将serviceUrl指向peer1

spring:
  application:
    name: eureka-server

server:
  port: 1112

eureka:
  instance:
    hostname: peer2
  client:
    serviceUrl:
      defaultZone: http://localhost:1111/eureka/

3.使用spring.profiles.active属性来分别启动peer1和peer2,
        java -jar eureka-server-1.0.0.jar 
        项目中添加spring-boot-maven-plugin依赖,不然导出的jar运行时会报出jar文件没有主清单属性。
        此时访问peer1的注册中心http://localhost:1111/eureka/如下 :registered-replicas中已经有peer2节点的eureka-server了,同样访问peer2的注册中心 http://localhost:1112/eureka/也能看到registered-replicas中已经有peer1节点的eureka-server.而且这些节点在可用分片(available-replicase)之中。

springcloud进阶之eureka集群配置,实现高可用

 4.在设置了多个服务注册中心之后,服务提供方还需要将服务注册到Eureka Server集群中,以消费者consumer1为例,修改application.yml配置文件    

eureka:
  client:
    fetch-registry: true
    register-with-eureka: true
    serviceUrl:
     defaultZone: http://localhost:1111/eureka/,http://localhost:1112/eureka/
server:
    port: 7002
spring:
  application:
    name: springcloud-consumer-test

       上面的配置主要对eureka.client.serviceUrl.defaultZone属性进行了改动,将注册红心指向了之前我们搭建的peer1和peer2,启动该服务,通过访问http://localhost:1111/eureka/和 http://localhost:1112/eureka/ ,可以观察到springcloud-consumer-test服务被同事注册到了peer1和peer2上,若此时断开peer1,由于consumer1同时也注册在了peer2中,其他服务依然能访问到springcloud-consumer-test,从而实现了服务注册中心的高可用。
    5.如果我们使用主机名来定义注册中心的地址,也可以使用IP地址的形式,但是需要在配置文件中添加配置参数eureka.instance.prefer-ip-address=true,此默认值为false