SpringCloud-eureka服務註冊發現以及消費流程

瑞莫蒂發表於2024-07-21

服務註冊中心 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

相關文章