消费端添加依赖:

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-eureka</artifactId>
  4. </dependency>

注册到注册中心

  1. eureka:
  2. instance:
  3. prefer-ip-address: true #显示IP地址
  4. instance-id: provider8001 #修改别名
  5. client:
  6. service-url:
  7. defaultZone: http://localhost:7001/eureka

启动类添加注解

增加@EnableEurekaClient注解

  1. @SpringBootApplication
  2. @EnableEurekaClient
  3. public class ProviderApp {
  4. public static void main(String[] args) {
  5. SpringApplication.run(Provider8001_APP.class,args);
  6. }
  7. }

服务发现

介绍

系统中的微服务可以通过Eureka的服务发现去获得在Eureka中注册的服务的信息,这是一个对外暴露的接口。

使用方法(provider中)

注入DiscoveryClient 对象(spring包下的),在controller方法中获取

  1. @Autowired
  2. private DiscoveryClient discoveryClient;
  3. @ResponseBody
  4. @GetMapping("/provider/discovery")
  5. public Object discovery(){
  6. List<String> list = discoveryClient.getServices();
  7. System.out.println(list);
  8. List<ServiceInstance> insList = discoveryClient.getInstances("MICROSERVICECLOUD-DEPT");
  9. for (ServiceInstance si:insList) {
  10. System.out.println(si.getHost() +"," + si.getServiceId() +"," +si.getPort() +"," +si.getUri() +"," +si.getMetadata());
  11. }
  12. return this.discoveryClient;
  13. }

启动类

在主启动类中加入@EnableDiscoveryClient注解