Eureka高可用实际上就是讲自己作为服务向其他服务注册中心注册自己,这样就可以形成一组互相注册的注册中心,以实现服务清单的互相同步,达到高可用的效果。
在Windows系统的C:\Windows\System32\drivers\etc\hosts写映射
127.0.0.1 slaveA
127.0.0.1 slaveB
注册中心(pom文件同上篇文章一样https://blog.csdn.net/qq_36594703/article/details/82558239):
server:
port: 8761
spring:
profiles: slaveA
eureka:
client:
serviceUrl:
defaultZone: http://slave2:8762/eureka
---
server:
port: 8762
spring:
profiles: slaveB
eureka:
client:
serviceUrl:
defaultZone: http://slave1:8761/eureka
@SpringBootApplication
@EnableEurekaServer
public class ServerApp {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
String profiles=scan.nextLine();
new SpringApplicationBuilder(ServerApp.class).profiles(profiles).run(args);
}
}
服务提供者也实现高可用(pom文件同上篇一样):
spring:
application:
name: first-police
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
@SpringBootApplication
@EnableEurekaClient
public class PoliceServer {
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
//读取控制台的端口输入
String port=scan.nextLine();
new SpringApplicationBuilder(PoliceServer.class).properties("server.port="+port).run(args);
}
}
服务消费者(pom文件同上篇一样,测试也同上篇一样):
server:
port: 9000
spring:
application:
name: first-person
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
用HttpClient模拟测试:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>cloud-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
</dependencies>
</project>
public class TestClient {
public static void main(String[] args) throws Exception{
CloseableHttpClient httpClient=HttpClients.createDefault();
for(int i=0;i<6;i++){
HttpGet httpget=new HttpGet("http://localhost:9000/router");
HttpResponse response=httpClient.execute(httpget);
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
}