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/wldatanode019@HXDI.COM";
        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();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值