java代码连接HBase(开启Kerberos和Sentry)

创建一个ZH_WG/wldatanode019的principal,并生成ZH_WG.keytab文件。
将hbase-site.xml和ZH_WG.keytab文件拷贝到conf目录下。注意,运行HBase代码的jar包放在当前目录下,而conf目录是当前目录的一个子目录。具体代码如下:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.security.UserGroupInformation;

import java.io.File;
import java.io.IOException;

public class HBaseSimple {
    private static Configuration conf = null;
    private static String confPath = System.getProperty("user.dir") + File.separator + "conf";

    public static void main(String[] args) throws IOException{
        String principal = "ZH_WG/[email protected]";
        String keytabPath = confPath + File.separator + "ZH_WG.keytab";

        conf = HBaseConfiguration.create();

        System.setProperty("java.security.krb5.conf", confPath + File.separator + "krb5.conf");
        conf.addResource(new Path(confPath + File.separator + "hbase-site.xml"));
        conf.set("hadoop.security.authentication" , "Kerberos" );

        UserGroupInformation. setConfiguration(conf);
        try {
            UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keytabPath);
            UserGroupInformation.setLoginUser(ugi);
        }
        catch (IOException e) {
            throw new RuntimeException("Kerberos 身份认证失败:" + e.getMessage(), e);
        }

        createTable();

    }

    public static void createTable() throws IOException {
        Connection connection = ConnectionFactory.createConnection(conf);
        System.out.println("HBase connected");
        Admin admin = connection.getAdmin();
        TableName tableName = TableName.valueOf("test1");

        HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
        HColumnDescriptor columnDescriptor1 = new HColumnDescriptor("c1");
        HColumnDescriptor columnDescriptor2 = new HColumnDescriptor("c2");

        tableDescriptor.addFamily(columnDescriptor1);
        tableDescriptor.addFamily(columnDescriptor2);

        admin.createTable(tableDescriptor);
        System.out.println("Table created");

        admin.close();
        connection.close();
    }
}

你可能感兴趣的:(CDH实操)