文档首页> MapReduce服务 MRS> 组件操作指南(LTS版)(巴黎区域)> 使用ZooKeeper> 在同个JVM对不同ZooKeeper客户端进行特殊配置
更新时间:2022-12-14 GMT+08:00

在同个JVM对不同ZooKeeper客户端进行特殊配置

配置场景

目前ZooKeeper客户端属性只能通过Java系统属性进行配置。因此,在同一个JVM的所有客户端具有相同的配置。在有些情况下,ZooKeeper客户端需要连接到不同的集群,并且需要不同的客户端配置。例如,用户要从相同的JVM连接两个不同的ZooKeeper集群,其中,一个集群是安全的,另一个集群是普通的。每个客户端的配置都是不同的。需要支持对不同客户端进行不同配置的方法。

这个方案允许每个ZooKeeper客户端使用不同的配置。如图1所示,每个客户端使用了不同的配置,这些配置在属性文件中进行初始化。
图1 在同个JVM对不同ZooKeeper客户端进行配置

配置描述

  1. 创建客户端特殊配置,必须创建ZKClientConfig对象,并且在创建ZooKeeper实例时,将ZKClientConfig对象传递到ZooKeeper。

    以下是创建ZKClientConfig实例的不同方法:

    • 方法1:
      ZKClientConfig clientConfig = new ZKClientConfig();

      这里,clientConfig将具有所有Java配置的ZooKeeper客户端属性。

    • 方法2:
      ZKClientConfig clientConfig = new ZKClientConfig();
      clientConfig.addConfiguration("/somepath/zoo-client.cfg");

      这里,clientConfig在“zoo-client.cfg”文件中初始化。“zoo-client.cfg”文件的属性将会覆盖相同的Java系统属性。

    • 方法3:
      ZKClientConfig clientConfig = new ZKClientConfig();
      clientConfig.setProperty(ZKClientConfig.SECURE_CLIENT, "true");

      这里,clientConfig经过初始化之后具有Java系统属性,同时通过代码clientConfig.setProperty(ZKClientConfig.SECURE_CLIENT, "true")增加了额外的属性ZKClientConfig.SECURE_CLIENT。

  2. 配置创建好之后,使用下列任意一个ZooKeeper API接口创建客户端。

    org.apache.zookeeper.ZooKeeper.ZooKeeper(String, int, Watcher, ZKClientConfig)
    org.apache.zookeeper.ZooKeeper.ZooKeeper(String, int, Watcher, boolean, ZKClientConfig)

样例代码

使用下列代码片段,配置Client1和Client2从同一个JVM分别连接到安全模式集群和普通模式集群。

  • 连接到安全模式集群:
    String secureClientConfigPath = "/somepath/zoo-secure-client.cfg";
    ZKClientConfig secureClientConfig = new ZKClientConfig(secureClientConfigPath);
    ZooKeeper secureZooKeeperClient = new ZooKeeper(connectString, sessionTimeout, watcher, secureClientConfig);
  • 连接到普通模式集群:
    String nonSecureClientConfigPath = "/somepath/zoo-non-secure-client.cfg";
    
    File nonSecureConfigFile = new File(nonSecureClientConfigPath);
    ZKClientConfig nonSecureClientConfig = new ZKClientConfig(nonSecureConfigFile);
    ZooKeeper nonSecureZooKeeperClient = new ZooKeeper(connectString, sessionTimeout, watcher, nonSecureClientConfig);

约束条件

当Kerberos域不同时,我们能通过域匹配到KDC。因此可基于各自客户端域名的KDC进行认证。

例如支持两个KDC运行在192.168.1.2和192.168.1.3,这两个KDC分别对应各自的域为HADOOP.COM和EXAMPLE.COM。

我们可以在krb5.conf文件中通过域匹配到KDC,如下所示。

[realms] 
HADOOP.COM = { 
kdc=192.168.1.2 
admin_server=192.168.1.2 
other attributes ... 
}
EXAMPLE.COM = {
kdc=192.168.1.3 
admin_server=192.168.1.3
other attributes ... 
} 

但当不同的KDC有相同的域时,域不能匹配到对应的KDC。这就是同一个JVM的多ZooKeeper客户端的配置约束。因为这个约束,同一个JVM的多ZooKeeper客户端,不能配置相同域的多个KDC。