使用 Zookeeper 進行服務發現

服務發現是基於微服務架構的關鍵原則之一。嘗試手動配置每個客戶端或某種形式的約定可能很難實現,而且可能很脆弱。Curator(一個用於 Zookeeper 的 Java 庫)透過服務發現擴充套件提供服務發現。Spring Cloud Zookeeper 使用此擴充套件進行服務註冊和發現。

啟用

包含 org.springframework.cloud:spring-cloud-starter-zookeeper-discovery 的依賴項將啟用自動配置,該自動配置會設定 Spring Cloud Zookeeper Discovery。

對於 Web 功能,您仍然需要包含 org.springframework.boot:spring-boot-starter-web
使用 Zookeeper 3.4 版本時,您需要更改包含依賴項的方式,如此處所述。

註冊到 Zookeeper

當客戶端註冊到 Zookeeper 時,它會提供關於自身的元資料(例如主機和埠、ID 和名稱)。

以下示例顯示了一個 Zookeeper 客戶端

@SpringBootApplication
@RestController
public class Application {

    @RequestMapping("/")
    public String home() {
        return "Hello world";
    }

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

}
上述示例是一個普通的 Spring Boot 應用程式。

如果 Zookeeper 位於 localhost:2181 之外的其他位置,則配置必須提供伺服器的位置,如以下示例所示

application.yml
spring:
  cloud:
    zookeeper:
      connect-string: localhost:2181
如果您使用Spring Cloud Zookeeper Config,則上述示例中顯示的值需要放在 bootstrap.yml 中,而不是 application.yml 中。

預設的服務名稱、例項 ID 和埠(取自 Environment)分別為 ${spring.application.name}、Spring 上下文 ID 和 ${server.port}

在類路徑中包含 spring-cloud-starter-zookeeper-discovery 會使應用程式既成為 Zookeeper“服務”(即它自己註冊)又成為“客戶端”(即它可以查詢 Zookeeper 以定位其他服務)。

如果您想停用 Zookeeper Discovery 客戶端,可以將 spring.cloud.zookeeper.discovery.enabled 設定為 false

使用 DiscoveryClient

Spring Cloud 透過Spring Cloud Loadbalancer支援 OpenFeign(一個 REST 客戶端構建器)、RestTemplateWebClient,使用邏輯服務名稱而不是物理 URL。

您還可以使用 org.springframework.cloud.client.discovery.DiscoveryClient,它為發現客戶端提供了不特定於 Netflix 的簡單 API,如以下示例所示

@Autowired
private DiscoveryClient discoveryClient;

public String serviceUrl() {
    List<ServiceInstance> list = discoveryClient.getInstances("STORES");
    if (list != null && list.size() > 0 ) {
        return list.get(0).getUri().toString();
    }
    return null;
}
© . This site is unofficial and not affiliated with VMware.