github地址:https://github.com/heumanpub/spring-cloud-example,后续会持续更新其它Spring Cloud组件应用。
1、环境
JDK:1.8,Spring Boot:2.0.6-RELEASE,Eureka:2.0.2-RELEASE。Spring Boot版本和Eureka版本一定要兼容,不然可能出现一系列莫名其妙的错误,版本兼容性可以查看Spring Cloud官网资料(http://spring.io/projects/spring-cloud)。这里列出部分:
Spring Cloud | Greenwich | Finchley | Edgware | Dalston |
Spring Boot | 2.1.x | 2.0.x | 1.5.x | 1.5.x |
Eureka | 未列出 | 2.0.2.RELEASE | 1.4.6.RELEASE | 未列出 |
2、项目搭建
新建一个maven项目,pom添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
添加Spring Boot的插件:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Spring Boot 启动类:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
if (NetworkUtil.isUsed("localhost", 8761)) {
System.setProperty("spring.profiles.active", "8762");
} else {
System.setProperty("spring.profiles.active", "8761");
}
SpringApplication.run(EurekaServerApplication.class, args);
}
}
// NetworkUtil类的isUsed方法是判断主机端口是否被占用,代码如下:
public static boolean isUsed(String hostname, int port) {
try {
Socket socket = new Socket(hostname, port);
try {
socket.close();
} catch (IOException e) {
// ignore
}
return true;
} catch (IOException e) {
return false;
}
}
application.yml文件配置:
# 配置两台Eureka Server,相互注册
eureka:
client:
service-url:
defaultZone: http://localhost2:8761/eureka/,http://localhost3:8762/eureka/
# 当spring.profiles.active=8761时使用以下配置
---
spring:
profiles: 8761
application:
name: eureka-server-1
server:
port: ${spring.profiles}
eureka:
instance:
hostname: localhost2
# 当spring.profiles.active=8762时使用以下配置
---
spring:
profiles: 8762
application:
name: eureka-server-2
server:
port: ${spring.profiles}
eureka:
instance:
hostname: localhost3
3、启动测试
(1)把该项目用到的域名映射到本地,比如Windows系统在hosts文件中增加一行
127.0.0.1 localhost2 localhost3
(2)IDE中使项目实例可以启动多个,先后启动该项目两次,第一个启动的项目控制台会输出很多异常堆栈,如果是连接超时、连接被拒之类的不用担心,因为第二个项目实例还未完成启动,待第二个启动成功之后即会正常。
(3)打开浏览器,分别查看两个项目的Eureka监控信息
4、其他
(1)如果是单机测试,需要修改一些配置不注册自己并关闭同步功能:
eureka:
client:
registerWithEureka: false
fetchRegistry: false
(2)Eureka的service-url的格式为http://${eureka.instance.hostname}:${server.port}/${server.servlet.context-path}/eureka
如有错误之处,欢迎留言指正!