使用JAVA语言操作Hbase

本文介绍了一个自定义的HBase工具类HBaseUtil,通过该工具类可以方便地实现HBase数据库的表创建、删除、数据插入、查询等功能。文章详细展示了如何使用Java API与HBase交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面我自定义了一个工具类HBaseUtil,通过该类可以方便的对hbase数据库进行增删改查。

package com.demo;

import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
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.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

public class HBaseUtil {
    // 与HBase数据库的连接对象
    Connection connection;
    // 数据库元数据操作对象
    Admin admin;

    /**
     * 初始化设置
     * @throws Exception
     */
    public void setup() throws Exception
    {
        // 取得一个数据库连接的配置参数对象
        Configuration conf=HBaseConfiguration.create();

        // 设置连接参数:HBase数据库所在的主机IP
        conf.set("hbase.zookeeper.quorum", "hadoop5,hadoop6,hadoop7");

        // 设置连接参数:HBase数据库使用的端口
        conf.set("hbase.zookeeper.clientPort", "2181");

        // 取得一个数据库连接对象
        this.connection=ConnectionFactory.createConnection(conf);

        // 取得一个数据库元数据操作对象
        this.admin=this.connection.getAdmin();
    }

    /**
     * 创建表
     * @param tableNameString
     * @param columnFamilies
     * @throws Exception
     */
    public void createTable(String tableNameString,String[] columnFamilies) throws Exception
    {
        // 新建一个数据表表名对象
        TableName tableName=TableName.valueOf(tableNameString);

        // 如果需要新建的表已经存在
        if (this.admin.tableExists(tableName))
        {
            System.out.println("表 "+tableNameString+" 已经存在!");
        } else {// 如果需要新建的表不存在
            // 数据表描述对象
            HTableDescriptor tableDescriptor=new HTableDescriptor(tableNameString);

            for(int i=0;i<columnFamilies.length;i++)
            {
                // 列族描述对象
                HColumnDescriptor columnDescriptor=new HColumnDescriptor(columnFamilies[i]);
                // 在数据表中添加一个列族
                tableDescriptor.addFamily(columnDescriptor);
            }

            // 新建数据表
            admin.createTable(tableDescriptor);

            try {
                admin.getTableDescriptor(tableName);
                System.out.println("表 "+tableNameString+" 创建成功!");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("表 "+tableNameString+" 创建失败!");
            }
        }
    }

    /**
     * 删除表
     * @param tableNameString
     * @throws Exception
     */
    public void dropTable(String tableNameString) throws Exception
    {
        //禁用表
        this.admin.disableTable(TableName.valueOf(tableNameString));

        //删除表
        this.admin.deleteTable(TableName.valueOf(tableNameString));
    }



    /**
     * 查询整表数据
     * @param tableNameString
     * @throws Exception
     */
    public void queryTable(String tableNameString) throws Exception
    {
        // 取得数据表对象
        Table table=this.connection.getTable(TableName.valueOf(tableNameString));

        ResultScanner resultScanner=table.getScanner(new Scan());

        for(Result result:resultScanner)
        {
            byte[] row = result.getRow();
            ;
            for (Cell cell : result.rawCells()) {
                System.out.println(Bytes.toString(row) +"\t\t"+
                                   Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength())+ ":"+
                                   Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength())+"="+
                                   Bytes.toString(cell.getValueArray(),cell.getValueOffset(),cell.getValueLength()));
            }
        }
    }

    /**
     * 获取指定rowkey的行数据
     * @param tableNameString
     * @param rowkey
     * @throws Exception
     */
    public void queryTableByRowkey(String tableNameString,String rowkey) throws Exception
    {
        // 取得数据表对象
        Table table=this.connection.getTable(TableName.valueOf(tableNameString));

        // 新建一个查询对象作为查询条件
        Get get=new Get(Bytes.toBytes(rowkey));

        // 按行键查询数据
        Result result=table.get(get);

        byte[] row=result.getRow();

        for(Cell cell:result.rawCells())
        {
            System.out.println(Bytes.toString(row) +"\t\t"+
                    Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength())+ ":"+
                    Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength())+"="+
                    Bytes.toString(cell.getValueArray(),cell.getValueOffset(),cell.getValueLength()));
        }

    }
    /**
     * 获取指定rowKey和列的数据,若列族存在多个版本,则会返回多行数据
     * @param tableNameString
     * @param rowkey
     * @param family
     * @param qualifier
     * @throws Exception
     */
    public void listCells(String tableNameString,String rowkey,String family,String qualifier) throws Exception
    {
        // 取得数据表对象
        Table table=this.connection.getTable(TableName.valueOf(tableNameString));

        // 新建一个查询对象作为查询条件
        Get get=new Get(Bytes.toBytes(rowkey));

        get.setMaxVersions(Integer.MAX_VALUE);

        Result result=table.get(get);

        for(Cell cell:result.getColumnCells(Bytes.toBytes(family), Bytes.toBytes(qualifier)))
        {
            System.out.println(family+":"+qualifier+"\t\t"+
                               "timestamp="+cell.getTimestamp()+"\t\t"+
                               "value="+Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
        }
    }

    /**
     * 获取指定rowkey和列的最新数据
     * @param tableNameString
     * @param rowkey
     * @param family
     * @param qualifier
     * @throws Exception
     */
    public void latestCells(String tableNameString,String rowkey,String family,String qualifier) throws Exception
    {
        // 取得数据表对象
        Table table=this.connection.getTable(TableName.valueOf(tableNameString));

        // 新建一个查询对象作为查询条件
        Get get=new Get(Bytes.toBytes(rowkey));

        Result result=table.get(get);

        Cell cell=result.getColumnLatestCell(Bytes.toBytes(family), Bytes.toBytes(qualifier));

        System.out.println(family+":"+qualifier+"\t\t"+
                   "timestamp="+cell.getTimestamp()+"\t\t"+
                   "value="+Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
    }

    /**
     * 清空表数据
     * @param tableNameString
     * @throws Exception
     */
    public void truncateTable(String tableNameString) throws Exception
    {
        // 取得目标数据表的表名对象
        TableName tableName=TableName.valueOf(tableNameString);

        this.admin.disableTable(tableName);

        // 清空指定表的数据
        this.admin.truncateTable(tableName, true);
    }

    //删除指定rowkey的行数据
    public void deleteByRowkey(String tableNameString,String rowkey) throws Exception
    {
        // 取得待操作的数据表对象
        Table table=this.connection.getTable(TableName.valueOf(tableNameString));

        // 创建删除条件对象
        Delete delete=new Delete(Bytes.toBytes(rowkey));

        // 执行删除操作
        table.delete(delete);
    }

    /**
     * 往数据表中插入数据
     * @param tableNameString
     * @throws Exception
     */
    public void insert(String tableNameString) throws Exception
    {
        // 取得一个数据表对象
        Table table=this.connection.getTable(TableName.valueOf(tableNameString));

        // 需要插入数据库的数据集合
        List<Put> putList=new ArrayList<Put>();

        Put put;

        for(int i=0;i<10;i++)
        {
            put=new Put(Bytes.toBytes("row"+i));
            put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("id"), Bytes.toBytes("value"+i));

            putList.add(put);
        }

        // 将数据集合插入到数据库
        table.put(putList);
    }

    /**
     * 给表添加列族
     * @param tableNameString
     * @param family
     * @throws Exception
     */
    public void addColumnFamily(String tableNameString,String family) throws Exception
    {
        // 取得目标数据表的表名对象
        TableName tableName=TableName.valueOf(tableNameString);

        // 创建列族对象
        HColumnDescriptor hcd=new HColumnDescriptor(family);

        // 将新创建的列族添加到指定的数据表
        this.admin.addColumn(tableName, hcd);
    }

    public void dropColumnFamily(String tableNameString,String family) throws Exception
    {
        // 取得目标数据表的表名对象
        TableName tableName=TableName.valueOf(tableNameString);
        this.admin.deleteColumn(tableName, Bytes.toBytes(family));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沉淀期待未来9527

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值