SpringCloud:Eureka注册中心集群化

郎家岭伯爵 2022年06月11日 367次浏览

背景

上一篇我们实现了基于Eureka的服务注册与发现,本文将实现Eureka注册中心的集群搭建。

实现

本文是基于上一篇的代码来进行的。

修改hosts文件

这里修改hosts文件只是便于观察集群效果。实际业务中这里应该是服务器的域名或者IP。

为了更加显著地看到效果,找到主机的hosts(C:\Windows\System32\drivers\etc)文件,并文件的末尾添加以下行,用于指定域名解析到本机。

注:

  • 修改hosts文件需要管理员权限,可在桌面编辑好文件内容后,替换原文件。
127.0.0.1	eureka7001.com
127.0.0.1	eureka7002.com
127.0.0.1	eureka7003.com

EurekaServer_7001模块

修改application.yaml

由于Eureka集群搭建需要模块之间相互注册,因此需要在前一篇application.yaml基础上修改以下内容:

重启模块

EurekaServer_7002模块

创建模块

编辑pom.xml

第一个Eureka模块与第二个的pom.xml依赖是一样的。

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka-server</artifactId>
   <version>1.4.6.RELEASE</version>
</dependency>

编辑application.yaml

server:
  port: 7002

# Eurake配置
eureka:
  instance:
    hostname: eureka7002.com # Eureka服务端的实例名称
  client:
    register-with-eureka: false # 是否需要向Eureka注册中心中注册自己
    fetch-registry: false # 如果为false,则表示自己为注册中心
    service-url: # 监控页面
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7003.com:7003/eureka/

创建启动类

package com.langjialing;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServer_7002 {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServer_7002.class, args);
    }
}

启动模块

EurekaServer_7003模块

创建模块

编辑pom.xml

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka-server</artifactId>
   <version>1.4.6.RELEASE</version>
</dependency>

编辑application.yaml

server:
  port: 7003

# Eurake配置
eureka:
  instance:
    hostname: eureka7003.com # Eureka服务端的实例名称
  client:
    register-with-eureka: false # 是否需要向Eureka注册中心中注册自己
    fetch-registry: false # 如果为false,则表示自己为注册中心
    service-url: # 监控页面
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

创建启动类

package com.langjialing;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServer_7003 {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServer_7003.class, args);
    }
}

启动模块

至此,Eureka集群已完成搭建,并相互注册成功!

总结

本文我们实现了Eureka注册中心的集群搭建,接下来我们将实现服务提供者的集群化。

赞助页面示例