您的位置:首页 > 编程语言 > Java开发

Spring Cloud入门二:eureka集群

2017-08-15 10:24 711 查看

Spring cloud eureka集群

Eureka帮助我们在spring cloud上进行服务注册和服务发现。但是,对于很多项目来说,只对服务在一个Spring Cloud Server注册是不合理的。当Server当掉时,服务将全部不能被发现。因此,我们在这里介绍对eureka进行集群,服务进行多注册。

多服务Server

新建两个Spring cloud Server项目,pom中添加依赖。

<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>


在resources文件夹下同时分别添加application-peer1.yml, application.yml文件,加入以下配置。分别表示服务注册中心url分别为http://peer2:1111/eureka/http://peer1:1110/eureka/

application-peer1.yml

spring:
application:
name: eureka-server
server:
port: 1110
eureka:
instance:
hostname: peer1
client:
service-url:
defaultZone: http://peer2:1111/eureka/[/code] 
application-peer2.yml


spring:
application:
name: eureka-server
server:
port: 1111
eureka:
instance:
hostname: peer2
client:
service-url:
defaultZone: http://peer1:1110/eureka/[/code] 
显然这里http://peer1:1110http://peer2:1111的peer1和peer2代表两个注册中心的ip地址,此时是不可用的。我们需要修改host文件,添加以下行:

127.0.0.1 peer1
127.0.0.1 peer2


在两个项目的application.yml分别激活其中一个配置文件

spring:
profiles:
active: peer1/peer2


在Application.java文件中,加入@EnableEurekaServer开启服务中心的功能。

启动项目,分别访问peer1:1110, peer2:1111





Eureka Client

新建Spring cloud Eureka client项目,pom中添加依赖

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>


修改application.yml,注册到http://peer2:1111/eureka/

spring:
application:
name: eureka-client
server:
port: 2222
eureka:
client:
service-url:
defaultZone: http://peer2:1111/eureka/[/code] 
在Application.java添加@EnableDiscoveryClient注册为client项目。

启动项目,分别访问服务注册中心。





关闭client注册到的peer2:1111,访问peer1,可以看到服务依然注册到。服务不会因为其中一个注册中心shutdown而关闭。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: