一、Eureka 是什么
Eureka 是 Netflix 开源的基于 REST 的服务治理方案,Spring Cloud 集成了 Eureka,提供服务治理和服务发现功能,可以和基于 Spring Boot 搭建的微服务应用轻松完成整合。
二、Spring Cloud Eureka 的组成
-
Eureka Server,注册中心
-
Eureka Client,所有要进行注册的微服务通过 Eureka Client 连接到 Eureka Server,完成注册
三、实战!快速搭建注册中心
- 创建一个父工程,pom.xml 配置如下
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- 在父工程下创建一个子工程 Module,pom.xml 配置如下
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
- 在子工程下创建 application.yml,添加 Eureka 相关的配置如下
server:
# 当前Eureka Server服务端口
port: 8761
eureka:
client:
# 是否将当前的Eureka Server服务作为客户端进行注册
register-with-eureka: false
# 是否获取其他Eureka Server服务的数据
fetch-registry: false
service-url:
# 注册中心的访问地址
defaultZone: http://localhost:8761/eureka/
属性说明
* server.port:当前 Eureka Server 服务端口
* eureka.client.register-with-eureka:是否将当前的 Eureka Server 服务作为客户端进行注册
* eureka.client.fetch-registry:是否获取其他 Eureka Server 服务的数据
* eureka.client.service-url.defaultZone:注册中心的访问地址
- 创建启动类
package com.frr;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekServerApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(EurekServerApplication.class, args);
}
}
注解说明
* @SpringBootApplication:声明该类是 Spring Boot 服务的入口
* @EnableEurekaServer:声明该类是一个 Eureka Server 微服务,提供服务注册和服务发现的功能,即注册中心
- 启动成功后的界面
四、总结
-
新建父工程,在 pom 文件中加入公用的依赖
-
在父工程中创建一个子工程 Module,在 Module 的 pom 文件中添加自己需要的组件依赖
-
在 Spring Boot 里面添加它的端口和 Eureka 相关的配置
-
最后创建启动类,在启动类添加注解,让当前这个工程成为一个 Eureka Server
从业务角度,我们将注册到服务中心的服务可分为服务提供者与服务消费者,那么服务提供者如何向其他服务提供服务呢,让我们期待下一篇Spring Cloud(三):Eureka Client 服务提供者
开发工程师一只,也在不断的学习阶段,平时的小经验不定期分享。 希望看我写的文字的人,可以少走弯路 祝工作学习顺利。
博主经验有限,若有不足,欢迎交流,共同改进~ 愿与同在CSDN的你共同进步。作者 | 甜蜜的小红薯
出品 | 小红薯