文章目录
My Name is YangYang
Eureka简介
在微服务架构中往往会有一个注册中心,每个微服务都会向注册中心去注册自己的地址及端口信息,注册中心维护着服务名称与服务实例的对应关系。每个微服务都会定时从注册中心获取服务列表,同时汇报自己的运行情况,这样当有的服务需要调用其他服务时,就可以从自己获取到的服务列表中获取实例地址进行调用,Eureka实现了这套服务注册与发现机制。
搭建Eureka注册中心
使用IDEA来创建SpringCloud应用
Eureka分为注册和发现,所以需要创建Server模块和Client模块,简单些讲实际项目中Eureka作为注册Server模块,其他子服务属于Client模块。
- 创建一个eureka-server模块,并使用Spring Initializer初始化一个SpringBoot项目
- 填写应用信息
- 选择你需要的SpringCloud组件进行创建
- 添加Pom.xml依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
- 在启动类上添加@EnableEurekaServer注解来启用Euerka注册中心功能
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
- 在配置文件application.yml中添加Eureka注册中心的配置
server:
port: 8001 #指定运行端口
spring:
application:
name: eureka-server #指定服务名称
eureka:
instance:
hostname: localhost #指定主机地址
client:
fetch-registry: false #指定是否要从注册中心获取服务(注册中心不需要开启)
register-with-eureka: false #指定是否要注册到注册中心(注册中心不需要开启)