目录

简介

搭建Eureka服务

注册服务到Eureka


简介

Eureka是Spring团队开发的服务治理中间件,可以轻松在项目中,实现服务的注册与发现,相比于阿里巴巴的Nacos、Apache基金会的Zookeeper,更加契合Spring项目,缺点就是仅仅只有服务发现与治理功能。

搭建Eureka服务

在项目中,创建一个新的Module,可以通过IDEA快速创建

点击Create即可创建一个Module,同时引入Eureka依赖。

在启动类中,添加@EnableEurekaServer注解

import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;@SpringBootApplication@EnableEurekaServerpublic class ServerEurekaApplication {public static void main(String[] args) {SpringApplication.run(ServerEurekaApplication.class, args);}}

在main文件中,创建资源文件夹resources,并创建application.yml文件,内容为

server:# 配置服务端口port: 8081eureka:client:service-url:# 配置eureka服务器地址defaultZone: http://127.0.0.1:${server.port}/eureka#是否需要将自己注册到注册中心(注册中心集群需要设置为true)register-with-eureka: false#是否需要搜索服务信息 因为自己是注册中心所以为falsefetch-registry: false

启动Module后,浏览器输入

http://localhost:8081/

即可打开Eureka

注册服务到Eureka

对于某个服务,注册到Eureka的流程如下:

【1】在该服务的启动类中添加@EnableEurekaClient注解

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

【2】在该服务的配置文件中,添加如下配置

server:# 服务端口号port: 8082spring:application:# 服务名称 - 服务之间使用名称进行通讯name: service-objcat-aeureka:client:service-url:# 填写注册中心服务器地址defaultZone: http://localhost:8081/eureka# 是否需要将自己注册到注册中心register-with-eureka: true# 是否需要搜索服务信息fetch-registry: trueinstance:# 使用ip地址注册到注册中心prefer-ip-address: true# 注册中心列表中显示的状态参数instance-id: ${spring.cloud.client.ip-address}:${server.port}

效果如下图:下图包含了2个服务,其中服务A有两个实例

可以通过Eureka,为某个微服务,指定多个实例,Eureka会轮询多个实例中可以正常提供服务的实例,从而实现分流。