Zookeeper

1 介绍

Apache ZooKeeper是Apache软件基金会的一个软件项目,它为大型分布式计算提供开源的分布式配置服务、同步服务和命名注册。 ZooKeeper曾经是Hadoop的一个子项目,但现在是一个独立的顶级项目。

ZooKeeper的架构通过冗余服务实现高可用性。因此,如果第一次无应答,客户端就可以询问另一台ZooKeeper主机。ZooKeeper节点将它们的数据存储于一个分层的名字空间,非常类似于一个文件系统或一个前缀树结构。客户端可以在节点读写,从而以这种方式拥有一个共享的配置服务。更新是全序的。

2 使用说明 - Java

在此查看完整示例代码

2.1 增加 Maven 依赖

<properties>
    <dubbo.version>3.1.6</dubbo.version>
</properties>

<dependencies>
    <!-- This dependency helps to introduce Curator and Zookeeper dependencies that are necessary for Dubbo to work with zookeeper as transitive dependencies  -->
    <dependency>
        <groupId>org.apache.dubbo</groupId>
        <artifactId>dubbo-dependencies-zookeeper</artifactId>
        <version>${dubbo.version}</version>
        <type>pom</type>
    </dependency>
</dependencies>

dubbo-dependencies-zookeeper 将自动为应用增加 Zookeeper 相关客户端的依赖,减少用户使用 Zookeeper 成本,如使用中遇到版本兼容问题,用户也可以不使用 dubbo-dependencies-zookeeper,而是自行添加 Curator、Zookeeper Client 等依赖。

由于 Dubbo 使用 Curator 作为与 Zookeeper Server 交互的编程客户端,因此,要特别注意 Zookeeper Server 与 Dubbo 版本依赖的兼容性

Zookeeper Server 版本Dubbo 版本Dubbo Zookeeper 依赖包说明
3.4.x 及以下3.0.x 及以上dubbo-dependencies-zookeeper传递依赖 Curator 4.x 、Zookeeper 3.4.x
3.5.x 及以上3.0.x 及以上dubbo-dependencies-zookeeper-curator5传递依赖 Curator 5.x 、Zookeeper 3.7.x
3.4.x 及以上2.7.x 及以下dubbo-dependencies-zookeeper传递依赖 Curator 4.x 、Zookeeper 3.4.x
3.5.x 及以上2.7.x 及以下须自行添加 Curator、Zookeeper 等相关客户端依赖

2.2 配置并启用 Zookeeper

# application.yml
dubbo:
 metadata-report:
   address: zookeeper://localhost:2181

# dubbo.properties
dubbo.metadata-report.address=zookeeper://localhost:2181

<dubbo:metadata-report address="zookeeper://localhost:2181" />

address 是启用 zookeeper 注册中心唯一必须指定的属性,而在生产环境下,address 通常被指定为集群地址,如

address=zookeeper://10.20.153.10:2181?backup=10.20.153.11:2181,10.20.153.12:2181

protocol 与 address 分开配置的模式也可以,如

<dubbo:metadata-report protocol="zookeeper" address="10.20.153.10:2181,10.20.153.11:2181,10.20.153.12:2181" />

3 高级配置

3.1 认证与鉴权

如果 Zookeeper 开启认证,Dubbo 支持指定 username、password 的方式传入身份标识。

# application.yml
dubbo:
  metadata-report:
   address: zookeeper://localhost:2181
   username: hello
   password: 1234

也可以直接将参数扩展在 address 上 address=zookeeper://hello:1234@localhost:2181

3.2 分组隔离

通过指定 group 属性,可以在同一个 Zookeeper 集群内实现微服务地址的逻辑隔离。比如可以在一套集群内隔离出多套开发环境,在地址发现层面实现隔离。

# application.yml
dubbo:
  metadata-report:
   address: zookeeper://localhost:2181
   group: daily1

3.3 其他扩展配置

配置连接、会话过期时间

# application.yml
dubbo:
  metadata-report:
   address: zookeeper://localhost:2181
   timeout: 30 * 1000 # 连接超时时间,默认 30s
   session: 60 * 1000 # 会话超时时间,默认 60s

最后修改 March 1, 2023: Add /zh/ docs aliases (#2336) (f2070b3fdd)