- 加注解
@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/
TIPS
这里,大家可先不去探究registerWithEureka
以及fetchRegistry
究竟是什么鬼,笔者将在下一节为大家揭晓。
将应用注册到Eureka Server上
- 加依赖
<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首页变成类似如下界面:
配套代码
- GitHub:
- Eureka Server:https://github.com/eacdy/spring-cloud-study/tree/master/2018-Finchley/microservice-discovery-eureka
- microservice-provider-user:https://www.github.com/eacdy/spring-cloud-study/tree/master/2018-Finchley/microservice-provider-user
- microservice-consumer-movie:https://github.com/eacdy/spring-cloud-study/tree/master/2018-Finchley/microservice-consumer-movie
- Gitee:
- Eureka Server:https://gitee.com/itmuch/spring-cloud-study/tree/master/2018-Finchley/microservice-discovery-eureka
- microservice-provider-user:https://gitee.com/itmuch/spring-cloud-study/tree/master/2018-Finchley/microservice-provider-user
- microservice-consumer-movie:https://gitee.com/itmuch/spring-cloud-study/tree/master/2018-Finchley/microservice-consumer-movie