一、原理
如图所示,多台Server端之间相互注册(这里以两台Server为例),Client端向所有的Server端注册。
二、Server端配置
1. 添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency>
2. 使用@EnableEurekaServer注解,开启Server端
@EnableEurekaServer @SpringBootApplication public class TestEurekaApplication { public static void main(String[] args) { SpringApplication.run(QmkxServerEurekaApplication.class, args); } }
3. 增加配置
为了配置方便,这里使用主机名代替IP,此处以单机为例,若多台机器,改为相应IP即可。
hosts配置:
127.0.0.1 peer1
127.0.0.1 peer2
application-peer1.yml配置:
server:
port: 2181
eureka:
client:
service-url:
defaultZone: http://peer2:2182/eureka/
instance:
hostname: peer1
prefer-ip-address: true
application-peer2.yml配置:
server:
port: 2182
eureka:
client:
service-url:
defaultZone: http://peer1:2181/eureka/
instance:
hostname: peer2
prefer-ip-address: true
三、Client端配置
1. 添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
2. 使用@EnableDiscoveryClient注解,开启注册功能
@EnableDiscoveryClient @SpringBootApplication public class TestUserApplication { public static void main(String[] args) { SpringApplication.run(TestUserApplication.class, args); } }
3. 修改配置文件,添加所有的Server,用逗号隔开
# 注册中心 eureka: instance: prefer-ip-address: true client: service-url: defaultZone: http://peer1:2181/eureka/,http://peer2:2182/eureka/