1. 程式人生 > >Spring-Cloud-第十篇-高可用的服務註冊中心

Spring-Cloud-第十篇-高可用的服務註冊中心

文章 史上最簡單的 SpringCloud 教程 | 第一篇: 服務的註冊與發現(Eureka) 介紹了服務註冊與發現,其中服務註冊中心Eureka Server,是一個例項,當成千上萬個服務向它註冊的時候,它的負載是非常高的,這在生產環境上是不太合適的,這篇文章主要介紹怎麼將Eureka Server叢集化。

一、準備工作

Eureka can be made even more resilient and available by running multiple instances and asking them to register with each other. In fact, this is the default behaviour, so all you need to do to make it work is add a valid serviceUrl to a peer, e.g.

摘自官網

Eureka通過執行多個例項,使其更具有高可用性。事實上,這是它預設的熟性,你需要做的就是給對等的例項一個合法的關聯serviceurl。

這篇文章我們基於第一篇文章的工程,來做修改。

二、改造工作

在eureka-server工程中resources資料夾下,建立配置檔案application-peer1.yml:

server:
  port: 8761

spring:
  profiles: peer1
eureka:
  instance:
    hostname: peer1
  client:
    serviceUrl:
      defaultZone: http://peer2:8769/eureka/
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

並且建立另外一個配置檔案application-peer2.yml:


server:
  port: 8769

spring:
  profiles: peer2
eureka:
  instance:
    hostname: peer2
  client:
    serviceUrl:
      defaultZone: http://peer1:8761/eureka/
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

這時eureka-server就已經改造完畢。

ou could use this configuration to test the peer awareness on a single host (there’s not much value in doing that in production) by manipulating /etc/hosts to resolve the host names.

按照官方文件的指示,需要改變etc/hosts,linux系統通過vim /etc/hosts ,加上:

127.0.0.1 peer1
127.0.0.1 peer2
  • 1
  • 2

windows電腦,在c:/windows/systems/drivers/etc/hosts 修改。

這時需要改造下service-hi:

eureka:
  client:
    serviceUrl:
      defaultZone: http://peer1:8761/eureka/
server:
  port: 8762
spring:
  application:
    name: service-hi
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

三、啟動工程

啟動eureka-server:

java -jar eureka-server-0.0.1-SNAPSHOT.jar - -spring.profiles.active=peer1

java -jar eureka-server-0.0.1-SNAPSHOT.jar - -spring.profiles.active=peer2

這裡寫圖片描述

啟動service-hi:

java -jar service-hi-0.0.1-SNAPSHOT.jar

訪問:localhost:8761,如圖:

Paste_Image.png

你會發現註冊了service-hi,並且有個peer2節點,同理訪問localhost:8769你會發現有個peer1節點。

client只向8761註冊,但是你開啟8769,你也會發現,8769也有 client的註冊資訊。

個人感受:這是通過看官方文件的寫的demo ,但是需要手動改host是不是不符合Spring Cloud 的高上大?

Prefer IP Address

In some cases, it is preferable for Eureka to advertise the IP Adresses of services rather than the hostname. Set eureka.instance.preferIpAddress to true and when the application registers with eureka, it will use its IP Address rather than its hostname.

摘自官網

eureka.instance.preferIpAddress=true是通過設定ip讓eureka讓其他服務註冊它。也許能通過去改變去通過改變host的方式。

此時的架構圖:

有點醜e.png

Eureka-eserver peer1 8761,Eureka-eserver peer2 8769相互感應,當有服務註冊時,兩個Eureka-eserver是對等的,它們都存有相同的資訊,這就是通過伺服器的冗餘來增加可靠性,當有一臺伺服器宕機了,服務並不會終止,因為另一臺服務存有相同的資料。

四、參考文獻