Loading

SpringCloud-eureka服务注册发现以及消费流程

服务注册中心 eureka server

  1. 导入SpringCloud eureka依赖
  2. 添加@EnableEurekaServer注解开启服务注册中心功能
@EnableEurekaServer
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class)
                    .web(true).run(args);
    }
}
  1. 禁止该服务自我注册
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

服务提供者 eureka client

  1. 导入eureka依赖
  2. 添加@EnableDiscoveryClient注解,激活Eureka中的DiscoveryClient实现
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        new SpringApplicationBuilder(
            ComputeServiceApplication.class)
            .web(true).run(args);
    }
}

3.实现/请求处理接口,通过DiscoveryClient对象,在日志中打印出服务实例的相关内容。

@RestController
public class DcController {

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("/dc")
    public String dc() {
        String services = "Services: " + discoveryClient.getServices();
        System.out.println(services);
        return services;
    }

}
  1. 指定服务注册中心地址
spring.application.name=eureka-client
server.port=2001
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/

服务消费者(Feign调用)

  1. 导入eureka和feign依赖
  2. 通过@EnableFeignClients注解开启feign扫描客户端功能
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		new SpringApplicationBuilder(Application.class).web(true).run(args);
	}
}

3.创建一个Feign的客户端接口,通过@FeignClient注解指定调用服务名称

@FeignClient("eureka-client")
public interface DcClient {

    @GetMapping("/dc")
    String consumer();

}

4.通过Feign的客户端接口来调用服务提供方

@RestController
public class DcController {

    @Autowired
    DcClient dcClient;

    @GetMapping("/consumer")
    public String dc() {
        return dcClient.consumer();
    }

}

流程图

参考链接:https://www.didispace.com/spring-cloud/spring-cloud-starter-dalston-1.html

posted @ 2024-07-21 00:09  瑞莫蒂  阅读(45)  评论(0)    收藏  举报