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 注册服务器,那么默认情况只有第⼀台可⽤的服务器,存