75. Zookeeper 的服务发现

服务发现是基于微服务的体系结构的关键原则之一。尝试手动配置每个 Client 端或某种形式的约定可能很困难并且很脆弱。 Curator(Zookeeper 的 Java 库)通过服务发现扩展提供服务发现。 Spring Cloud Zookeeper 使用此扩展进行服务注册和发现。

75.1 Activating

包括对org.springframework.cloud:spring-cloud-starter-zookeeper-discovery的依赖项将启用自动配置,该自动配置可设置 Spring Cloud Zookeeper Discovery。

Note

对于 Web 功能,您仍然需要包含org.springframework.boot:spring-boot-starter-web

Warning

使用 Zookeeper 3.4 版时,您需要按照here所述更改包含依赖项的方式。

75.2 向 Zookeeper 注册

Client 端向 Zookeeper 注册时,它会提供有关其自身的元数据(例如主机和端口,ID 和名称)。

以下示例显示了 ZookeeperClient 端:

@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);
    }

}

Note

前面的示例是一个普通的 Spring Boot 应用程序。

如果 Zookeeper 位于localhost:2181以外的其他位置,则配置必须提供服务器的位置,如以下示例所示:

application.yml.

spring:
  cloud:
    zookeeper:
      connect-string: localhost:2181

Warning

如果使用Spring Cloud Zookeeper 配置,则上一个示例中显示的值必须位于bootstrap.yml而不是application.yml中。

默认服务名称,实例 ID 和端口(从Environment获取)分别为${spring.application.name},Spring Context ID 和${server.port}

在 Classpath 上具有spring-cloud-starter-zookeeper-discovery可使该应用程序同时成为 Zookeeper 的“服务”(即它自己注册)和“Client 端”(即,它可以查询 Zookeeper 来定位其他服务)。

如果要禁用 Zookeeper Discovery Client,可以将spring.cloud.zookeeper.discovery.enabled设置为false

75.3 使用 DiscoveryClient

Spring Cloud 使用逻辑服务名称而不是物理 URL 支持Feign(RESTClient 端生成器)和Spring RestTemplate

您还可以使用org.springframework.cloud.client.discovery.DiscoveryClient,它为发现 Client 端提供了一个不特定于 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;
}