HBase系列4-常用API

一. Hbase常用API介绍

image.png

二. Java API实操

备注:
我使用的CDH 6.3.1版本,Hbase版本 2.1.0-cdh6.3.1

2.1 pom文件配置

    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-client</artifactId>
      <version>2.1.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-server</artifactId>
      <version>2.1.0</version>
    </dependency>

2.2 API类

hbase_demo1

package com.bigdata.study.hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class hbase_demo1 {
     HBaseAdmin hBaseAdmin = null;
     Connection connection  = null;
     Configuration configuration = null;
     HTable hTable = null;

    hbase_demo1()   {
        configuration = HBaseConfiguration.create();
        configuration.set("hbase.zookeeper.quorum", "10.31.1.124,10.31.1.125,10.31.1.126");
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
        try {
            connection = ConnectionFactory.createConnection(configuration);
            hBaseAdmin = (HBaseAdmin) connection.getAdmin();
            //HTable hTable=(HTable) connection.getTable(TableName.valueOf(tableName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static hbase_demo1 instance = null;
    public static synchronized hbase_demo1 getInstance(){
        if (instance == null){
            instance = new hbase_demo1();
        }
        return instance;
    }

  public  boolean isTableExist(String tableName) throws IOException {
      try {
          HTable hTable=(HTable) connection.getTable(TableName.valueOf(tableName));
      } catch (IOException e) {
          e.printStackTrace();
      }
        return hBaseAdmin.tableExists(TableName.valueOf(tableName));
  }

  // 创建表
  public  void createTable(String tableName, String... columnFamily) throws IOException {
      // 判断表是否存在
      if ( isTableExist(tableName) ){
          System.out.println("表" + tableName + "已存在");
          // System.exit(0);
      } else {
          // 创建表属性对象,表名需要转字节
          HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
          // 创建多个列族
          for(String f: columnFamily){
              tableDescriptor.addFamily(new HColumnDescriptor(f));
          }
          // 创建表
          hBaseAdmin.createTable(tableDescriptor );
          System.out.println("创建" + tableName + "表成功");
      }
  }

  // 删除表
  public void dropTable(String tableName) throws IOException {

        if (isTableExist(tableName)){
          hBaseAdmin.disableTable(TableName.valueOf(tableName));
          hBaseAdmin.deleteTable(TableName.valueOf(tableName));
          System.out.println("表" + tableName + "删除成功");
      } else {
          System.out.println("表" + tableName + "不存在!");
      }
  }

  // 向表中插入数据
    public void addRowData(String tableName, String rowKey, String columnFamily, String column, String value) throws IOException {

        try {
            HTable hTable=(HTable) connection.getTable(TableName.valueOf(tableName));
            // 向表中插入数据
            // 像Put 对象中封装数据
            Put put = new Put(Bytes.toBytes(rowKey));
            put.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value));
            hTable.put(put);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("插入数据成功");
    }

    // 删除多行数据
    public void deleteMultiRow(String tableName, String... rows) throws IOException {
      //HTable hTable = new HTable(configuration, tableName);

      List<Delete> deleteList = new ArrayList<Delete>();
      for (String row : rows) {
          Delete delete = new Delete(Bytes.toBytes(row));
          deleteList.add(delete);
      }
        try {
            HTable hTable=(HTable) connection.getTable(TableName.valueOf(tableName));
            hTable.delete(deleteList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 获取所有数据
    public void getAllRows(String tableName) throws IOException{
      //HTable hTable = new HTable(configuration, tableName);
      // 得到用于扫描region的对象
        Scan scan = new Scan();
        // 使用HTable 得到 resultcanner实现类的对象
        try {
            HTable hTable=(HTable) connection.getTable(TableName.valueOf(tableName));
            ResultScanner resultScanner = hTable.getScanner(scan);

            for (Result result : resultScanner) {
                Cell[] cells = result.rawCells();
                for (Cell cell : cells){
                    // 得到rowkey
                    System.out.println("行键:" + Bytes.toString(CellUtil.cloneRow(cell)));
                    // 得到列族
                    System.out.println("列族:" + Bytes.toString(CellUtil.cloneFamily(cell)));
                    System.out.println("列:" + Bytes.toString(CellUtil.cloneQualifier(cell)));
                    System.out.println("值:" + Bytes.toString(CellUtil.cloneValue(cell)));

                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    // 获取某一行数据
    public void getRow(String tableName, String rowKey) throws IOException{
      //HTable table = new HTable(configuration, tableName);
      Get get = new Get(Bytes.toBytes(rowKey));
      // get.setMaxVersions(); 显示所有版本
        // get.setTimeStamp(); 显示指定时间的版本


        try {
            HTable hTable=(HTable) connection.getTable(TableName.valueOf(tableName));
            Result result = hTable.get(get);
            for (Cell cell : result.rawCells()) {
                System.out.println("行键:" + Bytes.toString(result.getRow()));
                System.out.println("列族:" + Bytes.toString(CellUtil.cloneFamily(cell)));
                System.out.println("列:" + Bytes.toString(CellUtil.cloneQualifier(cell)));
                System.out.println("值:" + Bytes.toString(CellUtil.cloneValue(cell)));
                System.out.println("时间戳:" + cell.getTimestamp());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }



    }

    // 获取某一行指定 "列族:列" 的数据
    public void getRowQualifier(String tableName, String rowKey, String family, String qualifier) throws IOException{
        //HTable table = new HTable(configuration, tableName);
        Get get = new Get(Bytes.toBytes(rowKey));
        get.setMaxVersions();
        //get.setTimestamp();

        get.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));

        try {
            HTable hTable=(HTable) connection.getTable(TableName.valueOf(tableName));
            Result result = hTable.get(get);
            for (Cell cell : result.rawCells()) {
                System.out.println("行键:" + Bytes.toString(result.getRow()));
                System.out.println("列族:" + Bytes.toString(CellUtil.cloneFamily(cell)));
                System.out.println("列:" + Bytes.toString(CellUtil.cloneQualifier(cell)));
                System.out.println("值:" + Bytes.toString(CellUtil.cloneValue(cell)));
                //System.out.println("时间戳:" + cell.getTimestamp());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void closeConn(){
        if (connection!=null){
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}

2.3 测试类

hbase_test1

package com.bigdata.study.hbase;

import java.io.IOException;

public class hbase_test1 {
    public static void main(String[] args) throws IOException {

        hbase_demo1 hd1 = new hbase_demo1();

        // 删除表
        hd1.dropTable("java_test1");

        // 创建表
        hd1.createTable("java_test1","info1","info2");

        // 像表中插入数据
        hd1.addRowData("java_test1","1001","info1","name","詹姆斯");
        hd1.addRowData("java_test1","1001","info1","sex","男");
        hd1.addRowData("java_test1","1001","info1","age","33");
        hd1.addRowData("java_test1","1001","info2","job","BasketBall");
        hd1.addRowData("java_test1","1002","info1","name","杜兰特");
        hd1.addRowData("java_test1","1002","info1","sex","男");
        hd1.addRowData("java_test1","1002","info1","age","32");
        hd1.addRowData("java_test1","1002","info2","job","BasketBall");

        // 获取所有数据
        hd1.getAllRows("java_test1");

        // 获取某一行数据
        hd1.getRow("java_test1","1001");

        // 获取某一行指定 “列族:列” 的数据
        hd1.getRowQualifier("java_test1","1001","info1","name");

        // 删除多行数据
        hd1.deleteMultiRow("java_test1","1001","1002");

        // 删除表
        hd1.dropTable("java_test1");

        // 关闭连接
        hd1.closeConn();
    }
}

测试记录:
image.png
image.png

FAQ

1. HBaseAdmin 调用错误

报错如下:
‘HBaseAdmin(org.apache.hadoop.hbase.client.ClusterConnection)’ is not public in ‘org.apache.hadoop.hbase.client.HBaseAdmin’. Cannot be accessed from outside package

参考博客:
https://blog.csdn.net/weixin_40126236/article/details/106715357

之前写的是HBase的老版本的代码,需要同步修改。

2. 类的问题

运行程序报错如下:
java.lang.NoSuchMethodError: org.apache.hadoop.security.authentication.util.KerberosUtil.hasKerberos

参考博客:
https://blog.csdn.net/yuyinghua0302/article/details/93755774
原来是Hbase已经集成有hadoop-comm的jar包,pom文件无需配置hadoop-comm,删除即可

3. 创建HTable失败

老版本写法:

HTable hTable = new HTable(configuration, tableName);

新版本写法:

try {
            HTable hTable=(HTable) connection.getTable(TableName.valueOf(tableName));
        } catch (IOException e) {
            e.printStackTrace();
        }

参考:

  1. https://blog.csdn.net/weixin_40126236/article/details/106715357
  2. https://blog.csdn.net/zhangshk_/article/details/83690790
  3. https://blog.csdn.net/yuyinghua0302/article/details/93755774
hbase-client-project-2.4.16.jar是一个用于连接HBase数据库的Java客户端项目。HBase是一个分布式、面向列的NoSQL数据库,它可以存储大规模数据,并提供高可靠性和高性能的数据访问。而hbase-client-project-2.4.16.jar则是用来连接HBase数据库的Java客户端库。通过这个库,开发人员可以在Java应用中方便地访问HBase数据库,进行数据的读取、写入和管理操作。 hbase-client-project-2.4.16.jar库提供了丰富的API,使得开发人员可以编写简洁、高效的代码来操作HBase数据库。通过这个库,可以轻松地建立与HBase集群的连接,创建、删除表格,进行数据的增删改查等操作。此外,hbase-client-project-2.4.16.jar也提供了一些高级特性,比如支持过滤器、批量操作、数据版本控制等功能,让开发人员能够更加灵活地利用HBase数据库进行数据处理。 除此之外,hbase-client-project-2.4.16.jar还支持与HBase的安全认证和权限控制,可以保障数据访问的安全性。开发人员可以使用这个库来编写安全的Java应用,确保对HBase数据库的数据进行合法、受控的访问。 总之,hbase-client-project-2.4.16.jar是一个强大、灵活的Java客户端库,为开发人员提供了便捷的方式来连接、操作HBase数据库。无论是小规模的应用还是大规模的数据处理需求,它都能够满足开发人员的要求,帮助他们更有效地利用HBase数据库。 (字数: 258)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值