1.服務端
需要創建2個eureka server應用,
1.1 創建eureka-server-ha-peer1-demo
1.引入pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
2.主類上添加註解@EnableEurekaServer
3. application.yml配置
server:
port: 9093
## 定義 應用名稱
spring:
application:
name: eureka-server-ha-peer1
## 公用 Eureka 配置
### 向註冊中心註冊
eureka:
client:
register-with-eureka: true
### 向獲取註冊信息(服務、實例信息)
fetch-registry: true
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:9094/eureka
instance:
hostname: peer2
#關閉管理端actuator的安全,即/env /health端口完全開放
#management.security.enabled 在spring-boot2.0時過時,使用如下配置代替
management:
endpoints:
web:
exposure:
include: "*"
peer2表示另一臺eureka server服務器的地址,如果是windows 系統,可通過修改C:\Windows\System32\drivers\etc下的hosts文件,將peer2指向本地:
127.0.0.1 peer1
127.0.0.1 peer2
1.2 創建eureka-server-ha-peer2-demo
此應用配置和peer1相同,只是將其defaultZone屬性指向peer1的地址即可,再改下端口和應用名
server:
port: 9094
## 定義 應用名稱
spring:
application:
name: eureka-server-ha-peer2
## 公用 Eureka 配置
### 向註冊中心註冊
eureka:
client:
register-with-eureka: true
### 向獲取註冊信息(服務、實例信息)
fetch-registry: true
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:9093/eureka
instance:
hostname: peer1
#關閉管理端actuator的安全,即/env /health端口完全開放
#management.security.enabled 在spring-boot2.0時過時,使用如下配置代替
management:
endpoints:
web:
exposure:
include: "*"
1.3 啓動
訪問http://localhost:9093,需要等待一會兒,讓兩個註冊中心相互發現註冊,如果項目剛啓動,就訪問url,那麼有可能只有其中一個註冊中心有實例,另一個直接都沒有。當訪問出現以下情況,表示成功。
2 客戶端
2.1 創建eureka-client-ha-demo
1. 引入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2. 主類上添加註解@EnableDiscoveryClient
3. 配置application.yml
server:
port: 8083
spring:
application:
name: eureka-client-ha
eureka:
client:
serviceUrl:
#配置多個eureka註冊中心
defaultZone: http://localhost:9094/eureka/,http://localhost:9093/eureka/
#關閉管理端actuator的安全,即/env /health端口完全開放
#management.security.enabled 在spring-boot2.0時過時,使用如下配置代替
management:
endpoints:
web:
exposure:
include: "*"
2.2 重新啓動這3個應用並訪問
訪問註冊中心:http://localhost:9093/和http://localhost:9094/,發現兩個註冊中心均註冊了eureka-client-ha的服務,表示沒有問題
2.3 附加
如果 Eureka 客戶端應⽤配置多個 Eureka 註冊服務器,那麼默認情況只有第⼀臺可⽤的服務器,存