什么是Eureka?
Eureka是Netflix开源的一款提供服务注册和发现的产品,它提供了完整的Service Registry和Service Discovery实现。也是springcloud体系中最重要最核心的组件之一 。
Eureka基本架构:
Eureka 的基本架构如图1 所示,其中主要包括以下 3 种角色。
Register Service:服务注册中心,它是一个 Eureka Server,提供服务注册和发现的功能。
Provider Service:服务提供者,它是一个 Eureka Client,提供服务 。
Consumer Service:服务消费者,它是一个 Eureka Cient,消费服务。
图1 服务的治理--服务的注册和发现
案例:
spring cloud已经帮我实现了服务注册中心,我们只需要很简单的几个步骤就可以完成。
1.添加依赖
<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>
2.添加EnableEurekaServer注解
@SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
3.配置文件在application.properties
spring.application.name=eureka-server server.port=8761 eureka.client.register-with-eureka=false #表示是否将自己注册到Eureka Server,默认为true。 eureka.client.fetch-registry=false #表示是否从Eureka Server获取注册信息,默认为true。 eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/ #设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址
启动工程,访问http://localhost:8761/,会出现下面的页面。
集群注册
双节点注册;
1.创建application-peer1.properties,作为peer1服务中心的配置,并将serviceUrl指向peer2
spring.application.name=eureka-server server.port=8761 eureka.instance.hostname=peer1 eureka.client.serviceUrl.defaultZone=http://peer2:8762/eureka/
2.创建application-peer2.properties,作为peer2服务中心的配置,并将serviceUrl指向peer1
spring.application.name=eureka-server server.port=8762 eureka.instance.hostname=peer2 eureka.client.serviceUrl.defaultZone=http://peer1:8761/eureka/3.host配置 修改C:\Windows\System32\drivers\etc下的hosts文件
127.0.0.1 peer1
127.0.0.1 peer2
4.打包启动
打包:
mvn clean package
分别以peer1和peer2配置信息启动eureka
java -jar eureka-server-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer1
java -jar eureka-server-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer2
出现如下图所示的:
集群结束。自己可以尝试下三个四个等多个节点。