ToB企服应用市场:ToB评测及商务社交产业平台

标题: HBase Java API编程-学习记录 [打印本页]

作者: 科技颠覆者    时间: 2024-11-25 20:41
标题: HBase Java API编程-学习记录
Hbase伪分布式情况部署见:Hbase情况部署
前置准备

启动hdfs和hbase并验证情况正常

启动服务

通过shell命令启动hdfs文件体系和hbase服务,jps下出现如下图所示的进程即为精确。
  1. start-all.sh   # 启动HDFS文件系统 (datanode, namenode, secondary namenode)
  2. start-hbase.sh   # 启动HBase服务 (HMaster, HRegionServer, HQuorumPeer)
  3. jps   # 查看当前运行的任务进程
复制代码

验证运行情况

进入hbase shell终端或进入hbase提供的web页面(HBase默认端口:16030),验证情况正常。

HBase web页面如下图所示

搭建HBase客户端

使用IDEA创建Maven项目


修改pom.xml配置文件

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

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

使用Java API操作HBase

Java毗连Hbase

  1. // 静态代码块
  2. static {
  3.     Configuration conf = HBaseConfiguration.create();
  4.     conf.set("hbase.zookeeper.quorum", "192.168.159.139");   //这里替换成自己Hbase的IP地址
  5.     try {
  6.         //创建HBase连接对象
  7.         connection = ConnectionFactory.createConnection(conf);
  8.     } catch (IOException ex) {
  9.         ex.printStackTrace();
  10.     }
  11. }
复制代码
创建命名空间

  1. public static void createNameSpace(String nameSpaceName) throws IOException {
  2.         if (nameSpaceName == null || nameSpaceName.isEmpty()) {
  3.             logger.error("namespace 不能为空!");
  4.             return;
  5.         }
  6.         Admin admin = connection.getAdmin();
  7.         NamespaceDescriptor.Builder builder = NamespaceDescriptor.create(nameSpaceName);
  8.         NamespaceDescriptor namespaceDescriptor = builder.build();
  9.         try {
  10.             admin.createNamespace(namespaceDescriptor);
  11.             logger.info("namespace: {} 创建成功", nameSpaceName);
  12.         } catch (NamespaceExistException e) {
  13.             logger.error("namespace 名字已存在!");
  14.         }
  15.     }
复制代码
运行截图:

Hbase中前后对比:

表的创建和删除

  1. // 表的创建和删除
  2.     public static void createTable() {
  3.         TableName tableName = TableName.valueOf("stu");
  4.         try (Admin admin = connection.getAdmin()) {
  5.             // 检查表是否存在
  6.             if (admin.tableExists(tableName)) {
  7.                 admin.disableTable(tableName);
  8.                 admin.deleteTable(tableName);
  9.                 logger.info(tableName.toString() + " exists, deleted it.");
  10.             }
  11.             // 创建表描述符
  12.             TableDescriptor tableDescriptor = TableDescriptorBuilder.newBuilder(tableName)
  13.                     .setColumnFamily(ColumnFamilyDescriptorBuilder.of("StuInfo"))
  14.                     .setColumnFamily(ColumnFamilyDescriptorBuilder.of("Grades"))
  15.                     .build();
  16.             // 创建表
  17.             admin.createTable(tableDescriptor);
  18.             logger.info("Table " + tableName + " created successfully.");
  19.         } catch (IOException e) {
  20.             logger.error("Error: " + e.getMessage());
  21.             e.printStackTrace();
  22.         }
  23.     }
复制代码
运行截图:

Hbase中前后对比:

插入数据

  1. // 数据插入
  2.     public static void addData() throws IOException {
  3.         Table table = connection.getTable(TableName.valueOf("stu"));
  4.         Put put1 = new Put(Bytes.toBytes("row1"));
  5.         put1.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Jack"));
  6.         put1.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("18"));
  7.         put1.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("90"));
  8.         put1.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("85"));
  9.         table.put(put1);
  10.         Put put2 = new Put(Bytes.toBytes("row2"));
  11.         put2.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Alice"));
  12.         put2.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("19"));
  13.         put2.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("88"));
  14.         put2.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("92"));
  15.         table.put(put2);
  16.         Put put3 = new Put(Bytes.toBytes("row3"));
  17.         put3.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Bob"));
  18.         put3.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("20"));
  19.         put3.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("95"));
  20.         put3.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("80"));
  21.         table.put(put3);
  22.         Put put4 = new Put(Bytes.toBytes("row4"));
  23.         put4.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Emma"));
  24.         put4.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("21"));
  25.         put4.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("82"));
  26.         put4.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("90"));
  27.         table.put(put4);
  28.         Put put5 = new Put(Bytes.toBytes("row5"));
  29.         put5.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("David"));
  30.         put5.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("22"));
  31.         put5.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("91"));
  32.         put5.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("88"));
  33.         table.put(put5);
  34.         logger.info("SUCCESS");
  35.         table.close();
  36.     }
复制代码
运行截图:

Hbase表中的变化:

数据查询

行键查询

  1. // 数据获取(通过行键查询)
  2.     public static void getData() throws IOException {
  3.         Table table = connection.getTable(TableName.valueOf("stu"));
  4.         Get get = new Get(Bytes.toBytes("row1"));
  5.         Result result = table.get(get);
  6.         for (Cell cell : result.rawCells()) {
  7.             System.out.println(CellUtil.getCellKeyAsString(cell));
  8.             System.out.println(new String(CellUtil.cloneQualifier(cell)));
  9.             System.out.println(new String(CellUtil.cloneValue(cell)));
  10.             System.out.println(cell.getTimestamp());
  11.             System.out.println("----------------------------");
  12.         }
  13.         table.close();
  14.     }
复制代码
运行截图:

全部查询

  1. // 全部查询
  2. public static void getDataAll() throws IOException {
  3.     Table table = connection.getTable(TableName.valueOf("stu"));
  4.     Scan scan = new Scan();
  5.     ResultScanner scanner = table.getScanner(scan);
  6.     for (Result result : scanner) {
  7.         for (Cell cell : result.rawCells()) {
  8.             System.out.println(CellUtil.getCellKeyAsString(cell));
  9.             System.out.println(new String(CellUtil.cloneQualifier(cell)));
  10.             System.out.println(new String(CellUtil.cloneValue(cell)));
  11.             System.out.println(cell.getTimestamp());
  12.             System.out.println("----------------------------");
  13.         }
  14.     }
  15.     scanner.close();
  16.     table.close();
  17. }
复制代码
运行截图:

特定前缀列查询

  1. // 使用ColumnPrefixFilter过滤器 查询特定列前缀的列
  2. public static void getDataWithColumnPrefixFilter() throws IOException {
  3.     Table table = connection.getTable(TableName.valueOf("stu"));
  4.     Filter filter = new ColumnPrefixFilter(Bytes.toBytes("na"));
  5.     Scan scan = new Scan();
  6.     scan.setFilter(filter);
  7.     ResultScanner scanner = table.getScanner(scan);
  8.     for (Result result : scanner) {
  9.         for (Cell cell : result.rawCells()) {
  10.             System.out.println(CellUtil.getCellKeyAsString(cell));
  11.             System.out.println(new String(CellUtil.cloneQualifier(cell)));
  12.             System.out.println(new String(CellUtil.cloneValue(cell)));
  13.             System.out.println(cell.getTimestamp());
  14.             System.out.println("----------------------------");
  15.         }
  16.     }
  17.     scanner.close();
  18.     table.close();
  19. }
复制代码
运行截图:

完整代码

  1. 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 {
  2.         if (nameSpaceName == null || nameSpaceName.isEmpty()) {
  3.             logger.error("namespace 不能为空!");
  4.             return;
  5.         }
  6.         Admin admin = connection.getAdmin();
  7.         NamespaceDescriptor.Builder builder = NamespaceDescriptor.create(nameSpaceName);
  8.         NamespaceDescriptor namespaceDescriptor = builder.build();
  9.         try {
  10.             admin.createNamespace(namespaceDescriptor);
  11.             logger.info("namespace: {} 创建成功", nameSpaceName);
  12.         } catch (NamespaceExistException e) {
  13.             logger.error("namespace 名字已存在!");
  14.         }
  15.     }
  16.     // 表的创建和删除
  17.     public static void createTable() {
  18.         TableName tableName = TableName.valueOf("stu");
  19.         try (Admin admin = connection.getAdmin()) {
  20.             // 检查表是否存在
  21.             if (admin.tableExists(tableName)) {
  22.                 admin.disableTable(tableName);
  23.                 admin.deleteTable(tableName);
  24.                 logger.info(tableName.toString() + " exists, deleted it.");
  25.             }
  26.             // 创建表描述符
  27.             TableDescriptor tableDescriptor = TableDescriptorBuilder.newBuilder(tableName)
  28.                     .setColumnFamily(ColumnFamilyDescriptorBuilder.of("StuInfo"))
  29.                     .setColumnFamily(ColumnFamilyDescriptorBuilder.of("Grades"))
  30.                     .build();
  31.             // 创建表
  32.             admin.createTable(tableDescriptor);
  33.             logger.info("Table " + tableName + " created successfully.");
  34.         } catch (IOException e) {
  35.             logger.error("Error: " + e.getMessage());
  36.             e.printStackTrace();
  37.         }
  38.     }
  39.     // 数据插入
  40.     public static void addData() throws IOException {
  41.         Table table = connection.getTable(TableName.valueOf("stu"));
  42.         Put put1 = new Put(Bytes.toBytes("row1"));
  43.         put1.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Jack"));
  44.         put1.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("18"));
  45.         put1.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("90"));
  46.         put1.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("85"));
  47.         table.put(put1);
  48.         Put put2 = new Put(Bytes.toBytes("row2"));
  49.         put2.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Alice"));
  50.         put2.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("19"));
  51.         put2.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("88"));
  52.         put2.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("92"));
  53.         table.put(put2);
  54.         Put put3 = new Put(Bytes.toBytes("row3"));
  55.         put3.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Bob"));
  56.         put3.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("20"));
  57.         put3.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("95"));
  58.         put3.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("80"));
  59.         table.put(put3);
  60.         Put put4 = new Put(Bytes.toBytes("row4"));
  61.         put4.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("Emma"));
  62.         put4.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("21"));
  63.         put4.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("82"));
  64.         put4.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("90"));
  65.         table.put(put4);
  66.         Put put5 = new Put(Bytes.toBytes("row5"));
  67.         put5.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("name"), Bytes.toBytes("David"));
  68.         put5.addColumn(Bytes.toBytes("StuInfo"), Bytes.toBytes("age"), Bytes.toBytes("22"));
  69.         put5.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("math"), Bytes.toBytes("91"));
  70.         put5.addColumn(Bytes.toBytes("Grades"), Bytes.toBytes("english"), Bytes.toBytes("88"));
  71.         table.put(put5);
  72.         logger.info("SUCCESS");
  73.         table.close();
  74.     }
  75.     // 全部查询    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();    }}
复制代码

@鲨鱼爱兜兜

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4