Spring Cloud之Eureka集群搭建

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 CloudGreenwichFinchleyEdgwareDalston
Spring Boot2.1.x2.0.x1.5.x1.5.x
Eureka未列出2.0.2.RELEASE1.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

 

如有错误之处,欢迎留言指正!

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值