本节讲解基于Eureka的服务发现。git
Eureka是Netflix开源的服务发现组件,自己是一个基于REST的服务,包含Server和Client两部分,Spring Cloud将它集成在子项目Spring Cloud Netflix中。github
拓展阅读spring
理解跟我学Spring Cloud(Finchley版)-04-服务注册与服务发现-原理剖析 所讲的服务发现原理后,咱们来编写基于Eureka的服务发现——首先编写一个Eureka Server,而后将前文的微服务都注册到Eureka Server上。app
加依赖ide
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> </dependencies>
加注解微服务
@SpringBootApplication @EnableEurekaServer public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } }
写配置测试
server: port: 8761 eureka: client: # 是否要注册到其余Eureka Server实例 register-with-eureka: false # 是否要从其余Eureka Server实例获取数据 fetch-registry: false service-url: defaultZone: http://localhost:8761/eureka/
TIPSfetch
这里,你们可先不去探究registerWithEureka
以及fetchRegistry
到底是什么鬼,笔者将在下一节为你们揭晓。url
加依赖code
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
加注解
@SpringBootApplication public class ProviderUserApplication { public static void main(String[] args) { SpringApplication.run(ProviderUserApplication.class, args); } }
注意:早期的版本(Dalston及更早版本)还需在启动类上添加注解@EnableDiscoveryClient
或@EnableEurekaClient
,从Edgware开始,该注解可省略。
添加配置:
spring: application: # 指定注册到eureka server上的服务名称,对于电影微服务,本系列将名称设为microservice-consumer-movie name: microservice-provider-user eureka: client: service-url: # 指定eureka server通讯地址,注意/eureka/小尾巴不能少 defaultZone: http://localhost:8761/eureka/ instance: # 是否注册IP到eureka server,如不指定或设为false,那就会注册主机名到eureka server prefer-ip-address: true
依次启动Eureka Server以及用户微服务、电影微服务;
访问http://localhost:8761
可观察到相似以下界面:
将用户微服务中止,可看到Eureka Server首页变成相似以下界面:
http://www.itmuch.com/spring-cloud/finchley-5/