MAPREDUCE服务 MRS-HBase访问多个ZooKeeper样例程序:代码样例

时间:2024-06-13 09:38:27

代码样例

以下代码片段在“hbase-zk-example\src\main\java\com\huawei\hadoop\hbase\example”包的“TestZKSample”类中,用户主要需要关注“login”“connectApacheZK”这两个方法。

    private static void login(String keytabFile, String principal) throws IOException {
        conf = HBaseConfiguration.create();
        //In Windows environment
        String confDirPath = TestZKSample.class.getClassLoader().getResource("").getPath() + File.separator;[1]
        //In Linux environment
        //String confDirPath = System.getProperty("user.dir") + File.separator + "conf" + File.separator;

        // Set zoo.cfg for hbase to connect to fi zookeeper.
        conf.set("hbase.client.zookeeper.config.path", confDirPath + "zoo.cfg");
        if (User.isHBaseSecurityEnabled(conf)) {
            // jaas.conf file, it is included in the client pakcage file
            System.setProperty("java.security.auth.login.config", confDirPath + "jaas.conf");
            // set the kerberos server info,point to the kerberosclient
            System.setProperty("java.security.krb5.conf", confDirPath + "krb5.conf");
            // set the keytab file name
            conf.set("username.client.keytab.file", confDirPath + keytabFile);
            // set the user's principal
            try {
                conf.set("username.client.kerberos.principal", principal);
                User.login(conf, "username.client.keytab.file", "username.client.kerberos.principal",
                    InetAddress.getLocalHost().getCanonicalHostName());
            } catch (IOException e) {
                throw new IOException("Login failed.", e);
            }
        }
    }
    private void connectApacheZK() throws IOException, org.apache.zookeeper.KeeperException {
        try {
            // Create apache zookeeper connection.
            ZooKeeper digestZk = new ZooKeeper("127.0.0.1:2181", 60000, null);
             LOG .info("digest directory:{}", digestZk.getChildren("/", null));
            LOG.info("Successfully connect to apache zookeeper.");
        } catch (InterruptedException e) {
            LOG.error("Found error when connect apache zookeeper ", e);
        }
    }
support.huaweicloud.com/devg-lts-mrs/mrs_07_080039.html