使用hbaseAPI访问受hadoop安全集群

隶属于文章系列:大数据安全实战 https://www.jianshu.com/p/76627fd8399c


注意:

  • 使用常量ConstantPool.KerberEnabled来控制是否开启Kerberos配置
  • 在常量代码中根据操作系统判断Kerberos配置文件的位置
  • 集群上hdfs、hbase的配置在代码中没写,是因为直接把hdfs-site.xml、hbase-site.xml放在了项目的resources目录下
import com.kdps.common.ConstantPool;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.security.UserGroupInformation;

import java.io.IOException;

import static org.apache.hadoop.security.UserGroupInformation.setConfiguration;

public class HbaseDao {
    // 声明静态配置
    static Configuration conf = null;

    static {
        conf = HBaseConfiguration.create();

        if (!ConstantPool.KerberEnabled) {
            setConfiguration(conf);
        } else {
            //conf.set("hbase.zookeeper.quorum", "localhost");
            //虽然hbase本身没有使用Kerberos验证  还是要使用配置文件来确定域
            if (System.getProperty("os.name").toLowerCase().startsWith
                    ("win")) {

                System.setProperty("java.security.krb5.conf",
                        ConstantPool.Krb5_Conf);
                // System.setProperty("java.security.krb5.conf",
                // "C:/Windows/pro/krb5.ini");
            } else {
                // linux系统可不设,其会自动去寻找 /etc/krb5.conf
                System.setProperty("java.security.krb5.conf",
                        "/etc/krb5.conf");
            }

            conf.set("hadoop.security.authentication", "kerberos");
            setConfiguration(conf);
            try {
                UserGroupInformation.loginUserFromKeytab(ConstantPool
                        .Hbase_Kerberos_Principal, ConstantPool
                        .Hbase_Key_Tab);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * 创建表
     * @tableName 表名
     * @family 列族列表
     */
    public static void creatTable(String tableName, String[] family)
            throws Exception {
        HBaseAdmin admin = new HBaseAdmin(conf);
        HTableDescriptor desc = new HTableDescriptor(tableName);
        for (int i = 0; i < family.length; i++) {
            desc.addFamily(new HColumnDescriptor(family[i]));
        }
        if (admin.tableExists(tableName)) {
            System.out.println("table Exists!");
            System.exit(0);
        } else {
            admin.createTable(desc);
            System.out.println("create table Success!");
        }
    }



    public static void main(String[] args) throws Exception {

        // 创建表
        String tableName = "blog2";
        String[] family = {"article", "author"};
        creatTable(tableName, family);

    }
}

你可能感兴趣的:(使用hbaseAPI访问受hadoop安全集群)