面试系列-使用java 重写 hbase api

本文提供了一个使用Java重写HBase API的具体示例,包括创建表、插入数据、查询数据、删除数据等核心操作,并展示了如何通过Java代码与HBase交互。

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

使用java 重写 hbase api
*

public class HBaseTest {
    public static Configuration conf = null;
    public static Admin admin;
    public static Connection connection;
    public static Table table;
    static {
        try {
            conf = HBaseConfiguration.create();
            connection = ConnectionFactory.createConnection(conf);
            // -----这两个在hbase-site.xml的配置文件中配置好便不需要在这里进行重新配置了
            // conf.set("hbase.zookeeper.quorum", "centosm");
            // conf.set("hbase.rootdir", "hdfs://centosm:9000/hbase");
            admin = connection.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 关闭连接
    public static void close() {
        try {
            if (admin != null) {
                admin.close();
            }
            if (null != connection) {
                connection.close();
            }
            if (table != null){
                table.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 创建一张表
     * @param myTableName
     * @param colFamily
     * @param deleteFlag  true:存在则删除再重建
     * @throws Exception
     */
    public static void creatTable(String myTableName, String[] colFamily, boolean deleteFlag) throws Exception {
        TableName tableName = TableName.valueOf(myTableName);
        if (admin.tableExists(tableName)) {
            if (!deleteFlag) {
                System.out.println(myTableName + " table exists!");
            } else {
                HBaseTest.deleteTable(myTableName); // 先删除原先的表
                HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
                for (String str : colFamily) {
                    HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(str);
                    hTableDescriptor.addFamily(hColumnDescriptor);
                }
                admin.createTable(hTableDescriptor);
                System.out.println(myTableName + "表创建成功。。。");
            }
        } else {
            HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
            for (String str : colFamily) {
                HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(str);
                hTableDescriptor.addFamily(hColumnDescriptor);
            }
            admin.createTable(hTableDescriptor);
            System.out.println(myTableName + "表创建成功。。。");
        }
        //close();
    }
    /**
     * 往表中添加数据(单条添加)
     */
    public static void inserData(String myTableName, String rowKey, String colFamily, String col, String val) {
        try {
            table = connection.getTable(TableName.valueOf(myTableName));
            Put put = new Put(Bytes.toBytes(rowKey));
            put.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(col), Bytes.toBytes(val));
            table.put(put);
            System.out.println("数据插入成功。。。rowkey为:" + rowKey);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //close();
        }
    }
    /**
     * 往表中批量添加数据
     */
    public static void batchInserData(String myTableName, String colFamily, String col, int insertNum) {
        try {
            table = connection.getTable(TableName.valueOf(myTableName));
            List<Put> list = new ArrayList<Put>();
            Put put;
            for (int i = 0; i < insertNum; i++) {
                put = new Put(Bytes.toBytes("rowKey" + i));
                put.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(col), Bytes.toBytes("110804" + i));
                list.add(put);
            }
            table.put(list);
            System.out.println("数据插入成功。。。");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // close();
        }
    }
    /**
     * 获取数据(根据行键获取其整行数据)
     */
    public static void getDataFromRowKey(String myTableName, String rowKey) {
        try {
            table = connection.getTable(TableName.valueOf(myTableName));
            Get get = new Get(Bytes.toBytes(rowKey));
            Result re = table.get(get);
            List<Cell> listCells = re.listCells();
            for (Cell cell : listCells) {
                System.out.println(new String(CellUtil.cloneRow(cell)) + "\t" + new String(CellUtil.cloneFamily(cell))
                        + "\t" + new String(CellUtil.cloneQualifier(cell)) + "\t"
                        + new String(CellUtil.cloneValue(cell)) + "\t" + cell.getTimestamp());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //close();
        }
    }
    /**
     * 根据表名与行键及列簇获取数据
     * @param myTableName
     * @param rowKey
     * @param colFamily
     * @param Col
     * @throws IOException
     */
    private static void getData(String myTableName, String rowKey, String colFamily, String col) throws IOException {
        table = connection.getTable(TableName.valueOf(myTableName));
        Get get = new Get(Bytes.toBytes(rowKey));
        get.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(col));
        Result re = table.get(get);
        if (re.isEmpty()){
            System.out.println("查询结果为空。。。。");
            return;
        }
        List<Cell> listCells = re.listCells();
        for (Cell cell : listCells) {
            System.out.println(new String(CellUtil.cloneRow(cell)) + "\t" + new String(CellUtil.cloneFamily(cell))
                    + "\t" + new String(CellUtil.cloneQualifier(cell)) + "\t"
                    + new String(CellUtil.cloneValue(cell)) + "\t" + cell.getTimestamp());
        }
       // close();
    }
    /**
     * 根据表名查询整张表的数据(当然同样可根据列簇,列分割符等进行scan的查询,这里不进行细写了)
     * @param tablename
     * @throws IOException
     */
    private static void getScanData(String tablename) throws IOException {
        table = connection.getTable(TableName.valueOf(tablename));
        ResultScanner scanner = table.getScanner(new Scan());
        Iterator<Result> it = scanner.iterator();
        while(it.hasNext()) {
            Result re = it.next();
            List<Cell> listCells = re.listCells();
            for (Cell cell : listCells) {
                System.out.println(new String(CellUtil.cloneRow(cell)) + "\t" + new String(CellUtil.cloneFamily(cell))
                        + "\t" + new String(CellUtil.cloneQualifier(cell)) + "\t"
                        + new String(CellUtil.cloneValue(cell)) + "\t" + cell.getTimestamp());
            }
        }
    }
    /**
     * 删除数据
     * @param tableName
     * @param rowKey
     * @throws IOException 
     */
    private static void delDByRowKey(String tableName, String rowKey) {
        try {
            table = connection.getTable(TableName.valueOf(tableName));
            Delete delete = new Delete(Bytes.toBytes(rowKey));
            table.delete(delete);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(tableName + " 表中rowKey为 " + rowKey + " 的数据已被删除....");
    }
    /**
     * 删除一张表
     * 
     * @param args
     */
    public static void deleteTable(String myTableName) {
        try {
            TableName tableName = TableName.valueOf(myTableName);
            admin.disableTable(tableName); // 删除表前先对表进行disable
            admin.deleteTable(tableName);
            System.out.println(tableName + " 表已被删除。。。");
        } catch (IOException e) {
            e.printStackTrace();
        }  finally {
            close();
        }
    }
    /**
     * 删除列簇
     * 
     * @param args
     */
    public static void deleteColumnFamily(String myTableName, byte[] colFamily) {
        try {
            TableName tableName = TableName.valueOf(myTableName);
            admin.disableTable(tableName); // 删除前先对表进行disable
            admin.deleteColumn(tableName, colFamily);
            System.out.println(tableName + " 表 " + colFamily + " 列已被删除。。。");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close();
        }
    }
    public static void main(String[] args) {
        try {
                // 创建表
                String tablename = "student"; 
//              String[] familys = { "grade","course" };
//              boolean booleanFlog = true;
//              HBaseTest.creatTable(tablename, familys, booleanFlog);
//           
//              /**
//               * 往表中插入数据:插入数据的时候指定数据所属的列簇与列分割符
//               */
//              
//               String rowKey = "ycb"; 
//               String colFamily = "course"; 
//               String col = "English"; 
//               String val = "88";
//               
//               String rowKey2 = "hehe"; 
//               String val2 = "89";
//               
//               HBaseTest.inserData(tablename, rowKey, colFamily, col, val);
//               HBaseTest.inserData(tablename, rowKey2, colFamily, col, val2);
//               
//
//              /**
//               * 根据表名与行键查询整行数据
//               */
//              
//               HBaseTest.getDataFromRowKey(tablename, rowKey);
//               HBaseTest.getDataFromRowKey(tablename, rowKey2);
//               
//              
//              /**
//               * 根据表名与行键及列簇获取数据
//               */
//              colFamily = "course";
//              col = "English";
//              HBaseTest.getData(tablename, rowKey, colFamily, col);
//              /**
//               * 查询整张表的数据
//               */
//              HBaseTest.getScanData(tablename);
//              
//              /**
//               * 根据rowkey删除指定数据
//               */
//              String rowKey = "ycb";
//              HBaseTest.delDByRowKey(tablename, rowKey);
//              /**
//               * 批量插入数据
//               */
//              String colFamily = "grade"; 
//              String col = "sid";
//              int inserNum = 10;
//              HBaseTest.batchInserData(tablename, colFamily, col, inserNum);

*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值