HBase Java API编程-学习记录

Hbase伪分布式环境部署见:Hbase环境部署

前置准备

启动hdfs和hbase并验证环境正常

启动服务

通过shell命令启动hdfs文件系统和hbase服务,jps下出现如下图所示的进程即为正确。

start-all.sh   # 启动HDFS文件系统 (datanode, namenode, secondary namenode)
start-hbase.sh   # 启动HBase服务 (HMaster, HRegionServer, HQuorumPeer)
jps   # 查看当前运行的任务进程

在这里插入图片描述

验证运行环境

进入hbase shell终端或进入hbase提供的web页面(HBase默认端口:16030),验证环境正常。
在这里插入图片描述

HBase web页面如下图所示

在这里插入图片描述

搭建HBase客户端

使用IDEA创建Maven项目

在这里插入图片描述

修改pom.xml配置文件

为项目添加hbase-lient的依赖(刷新完成不飘红即为引入成功)

在这里插入图片描述

添加log4j输出日志的依赖(刷新完成不飘红即为引入成功)

在这里插入图片描述

使用Java API操作HBase

Java连接Hbase

// 静态代码块
static {
    Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "192.168.159.139");   //这里替换成自己Hbase的IP地址
    try {
        //创建HBase连接对象
        connection = ConnectionFactory.createConnection(conf);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

创建命名空间

public static void createNameSpace(String nameSpaceName) throws IOException {
        if (nameSpaceName == null || nameSpaceName.isEmpty()) {
            logger.error("namespace 不能为空!");
            return;
        }
        Admin admin = connection.getAdmin();
        NamespaceDescriptor.Builder builder = NamespaceDescriptor.create(nameSpaceName);
        NamespaceDescriptor namespaceDescriptor = builder.build();
        try {
            admin.createNamespace(namespaceDescriptor);
            logger.info("namespace: {} 创建成功", nameSpaceName);
        } catch (NamespaceExistException e) {
            logger.error("namespace 名字已存在!");
        }
    }

运行截图:

在这里插入图片描述

Hbase中前后对比:

在这里插入图片描述

表的创建和删除

// 表的创建和删除
    public static void createTable() {
        TableName tableName = TableName.valueOf("stu");

        try (Admin admin = connection.getAdmin()) {
            // 检查表是否存在
            if (admin.tableExists(tableName)) {
                admin.disableTable(tableName);
                admin.deleteTable(tableName);
                logger.info(tableName.toString() + " exists, deleted it.");
            }
            // 创建表描述符
            TableDescriptor tableDescriptor = TableDescriptorBuilder.newBuilder(tableName)
                    .setColumnFamily(ColumnFamilyDescriptorBuilder.of("StuInfo"))
                    .setColumnFamily(ColumnFamilyDescriptorBuilder.of("Grades"))
                    .build();
            // 创建表
            admin.createTable(tableDescriptor);
            logger.info("Table " + tableName + " created successfully.");
        } catch (IOException e) {
            logger.error("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }

运行截图:

在这里插入图片描述

Hbase中前后对比:

在这里插入图片描述

插入数据

// 数据插入
    public static void addData() throws IOException {
        Table table = connection.getTable(TableName.valueOf("stu"));
        Put put1 = new Put(Bytes.toBytes("row1"));
        put1.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Jack"));
        put1.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("18"));
        put1.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("90"));
        put1.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("85"));
        table.put(put1);

        Put put2 = new Put(Bytes.toBytes("row2"));
        put2.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Alice"));
        put2.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("19"));
        put2.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("88"));
        put2.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("92"));
        table.put(put2);

        Put put3 = new Put(Bytes.toBytes("row3"));
        put3.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Bob"));
        put3.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("20"));
        put3.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("95"));
        put3.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("80"));
        table.put(put3);

        Put put4 = new Put(Bytes.toBytes("row4"));
        put4.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Emma"));
        put4.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("21"));
        put4.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("82"));
        put4.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("90"));
        table.put(put4);

        Put put5 = new Put(Bytes.toBytes("row5"));
        put5.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("David"));
        put5.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("22"));
        put5.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("91"));
        put5.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("88"));
        table.put(put5);
        logger.info("SUCCESS");
        table.close();
    }

运行截图:

在这里插入图片描述

Hbase表中的变化:

在这里插入图片描述

数据查询

行键查询

// 数据获取(通过行键查询)
    public static void getData() throws IOException {
        Table table = connection.getTable(TableName.valueOf("stu"));
        Get get = new Get(Bytes.toBytes("row1"));
        Result result = table.get(get);
        for (Cell cell : result.rawCells()) {
            System.out.println(CellUtil.getCellKeyAsString(cell));
            System.out.println(new String(CellUtil.cloneQualifier(cell)));
            System.out.println(new String(CellUtil.cloneValue(cell)));
            System.out.println(cell.getTimestamp());
            System.out.println("----------------------------");
        }
        table.close();
    }

运行截图:

在这里插入图片描述

全部查询

// 全部查询
public static void getDataAll() throws IOException {
    Table table = connection.getTable(TableName.valueOf("stu"));
    Scan scan = new Scan();
    ResultScanner scanner = table.getScanner(scan);
    for (Result result : scanner) {
        for (Cell cell : result.rawCells()) {
            System.out.println(CellUtil.getCellKeyAsString(cell));
            System.out.println(new String(CellUtil.cloneQualifier(cell)));
            System.out.println(new String(CellUtil.cloneValue(cell)));
            System.out.println(cell.getTimestamp());
            System.out.println("----------------------------");
        }
    }
    scanner.close();
    table.close();
}

运行截图:

在这里插入图片描述

特定前缀列查询

// 使用ColumnPrefixFilter过滤器 查询特定列前缀的列
public static void getDataWithColumnPrefixFilter() throws IOException {
    Table table = connection.getTable(TableName.valueOf("stu"));
    Filter filter = new ColumnPrefixFilter(Bytes.toBytes("na"));
    Scan scan = new Scan();
    scan.setFilter(filter);
    ResultScanner scanner = table.getScanner(scan);
    for (Result result : scanner) {
        for (Cell cell : result.rawCells()) {
            System.out.println(CellUtil.getCellKeyAsString(cell));
            System.out.println(new String(CellUtil.cloneQualifier(cell)));
            System.out.println(new String(CellUtil.cloneValue(cell)));
            System.out.println(cell.getTimestamp());
            System.out.println("----------------------------");
        }
    }
    scanner.close();
    table.close();
}

运行截图:

在这里插入图片描述

完整代码

package org.example;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;

public class HBaseDemo {
    private static Connection connection;
    private static final Logger logger = LogManager.getLogger(HBaseDemo.class);

    static {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "192.168.159.139");
        try {
            connection = ConnectionFactory.createConnection(conf);
            logger.info("Hbase 连接成功!");
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex);
        }
    }

    //创建命名空间
    public static void createNameSpace(String nameSpaceName) throws IOException {
        if (nameSpaceName == null || nameSpaceName.isEmpty()) {
            logger.error("namespace 不能为空!");
            return;
        }
        Admin admin = connection.getAdmin();
        NamespaceDescriptor.Builder builder = NamespaceDescriptor.create(nameSpaceName);
        NamespaceDescriptor namespaceDescriptor = builder.build();
        try {
            admin.createNamespace(namespaceDescriptor);
            logger.info("namespace: {} 创建成功", nameSpaceName);
        } catch (NamespaceExistException e) {
            logger.error("namespace 名字已存在!");
        }
    }

    // 表的创建和删除
    public static void createTable() {
        TableName tableName = TableName.valueOf("stu");

        try (Admin admin = connection.getAdmin()) {
            // 检查表是否存在
            if (admin.tableExists(tableName)) {
                admin.disableTable(tableName);
                admin.deleteTable(tableName);
                logger.info(tableName.toString() + " exists, deleted it.");
            }
            // 创建表描述符
            TableDescriptor tableDescriptor = TableDescriptorBuilder.newBuilder(tableName)
                    .setColumnFamily(ColumnFamilyDescriptorBuilder.of("StuInfo"))
                    .setColumnFamily(ColumnFamilyDescriptorBuilder.of("Grades"))
                    .build();
            // 创建表
            admin.createTable(tableDescriptor);
            logger.info("Table " + tableName + " created successfully.");
        } catch (IOException e) {
            logger.error("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 数据插入
    public static void addData() throws IOException {
        Table table = connection.getTable(TableName.valueOf("stu"));
        Put put1 = new Put(Bytes.toBytes("row1"));
        put1.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Jack"));
        put1.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("18"));
        put1.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("90"));
        put1.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("85"));
        table.put(put1);

        Put put2 = new Put(Bytes.toBytes("row2"));
        put2.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Alice"));
        put2.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("19"));
        put2.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("88"));
        put2.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("92"));
        table.put(put2);

        Put put3 = new Put(Bytes.toBytes("row3"));
        put3.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Bob"));
        put3.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("20"));
        put3.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("95"));
        put3.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("80"));
        table.put(put3);

        Put put4 = new Put(Bytes.toBytes("row4"));
        put4.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Emma"));
        put4.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("21"));
        put4.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("82"));
        put4.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("90"));
        table.put(put4);

        Put put5 = new Put(Bytes.toBytes("row5"));
        put5.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("David"));
        put5.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("22"));
        put5.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("91"));
        put5.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("88"));
        table.put(put5);
        logger.info("SUCCESS");
        table.close();
    }

    // 全部查询
    public static void getDataAll() throws IOException {
        Table table = connection.getTable(TableName.valueOf("stu"));
        Scan scan = new Scan();
        ResultScanner scanner = table.getScanner(scan);
        for (Result result : scanner) {
            for (Cell cell : result.rawCells()) {
                System.out.println(CellUtil.getCellKeyAsString(cell));
                System.out.println(new String(CellUtil.cloneQualifier(cell)));
                System.out.println(new String(CellUtil.cloneValue(cell)));
                System.out.println(cell.getTimestamp());
                System.out.println("----------------------------");
            }
        }
        scanner.close();
        table.close();
    }

    // 数据获取 - 行键
    public static void getDataRow() throws IOException {
        Table table = connection.getTable(TableName.valueOf("stu"));
        Get get = new Get(Bytes.toBytes("row1"));
        Result result = table.get(get);
        for (Cell cell : result.rawCells()) {
            System.out.println(CellUtil.getCellKeyAsString(cell));
            System.out.println(new String(CellUtil.cloneQualifier(cell)));
            System.out.println(new String(CellUtil.cloneValue(cell)));
            System.out.println(cell.getTimestamp());
            System.out.println("----------------------------");
        }
        table.close();
    }

    // 使用ColumnPrefixFilter过滤器 查询特定列前缀的列
    public static void getDataWithColumnPrefixFilter() throws IOException {
        Table table = connection.getTable(TableName.valueOf("stu"));
        Filter filter = new ColumnPrefixFilter(Bytes.toBytes("na"));
        Scan scan = new Scan();
        scan.setFilter(filter);
        ResultScanner scanner = table.getScanner(scan);
        for (Result result : scanner) {
            for (Cell cell : result.rawCells()) {
                System.out.println(CellUtil.getCellKeyAsString(cell));
                System.out.println(new String(CellUtil.cloneQualifier(cell)));
                System.out.println(new String(CellUtil.cloneValue(cell)));
                System.out.println(cell.getTimestamp());
                System.out.println("----------------------------");
            }
        }
        scanner.close();
        table.close();
    }

    public static void main(String[] args) throws IOException {
        // 创建命名空间
//        createNameSpace("test");
        // 表的创建和删除
//        createTable();
        // 数据插入
//        addData();
        // 数据获取
//        getDataRow();
        // 全部查询
//        getDataAll();
        // 使用PrefixFilter过滤器查询
//        getDataWithColumnPrefixFilter();
    }
}

在这里插入图片描述

@鲨鱼爱兜兜

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值