云数据库 HBase Java API

By | 2021年4月22日

HBase原生提供Java API进行数据访问管理,以下给出基本使用示例,更多内容可以参考Apache HBase API 手册

如果您使用的是HBase标准版,请参考JAVA API 访问来进行基本环境的配置。

如果您使用的是HBase增强版,请参考JAVA API 访问来进行基本环境的配置。

创建连接

通过配置conf创建Connection,标准版和增强版配置方式不同,请参考上面的链接

  
  1. // 创建 HBase连接,在程序生命周期内只需创建一次,该连接线程安全,可以共享给所有线程使用。
  2. // 在程序结束后,需要将Connection对象关闭,否则会造成连接泄露。
  3. // 也可以采用try finally方式防止泄露
  4. Connection connection = ConnectionFactory.createConnection(conf);

使用API

建立完连接后,即可使用Java API访问HBase增强版集群。下面提供一些简单的Java 示例。

DDL操作

  
  1. try (Admin admin = connection.getAdmin()){
  2. // 建表
  3. HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("tablename"));
  4. htd.addFamily(new HColumnDescriptor(Bytes.toBytes("family")));
  5. // 创建一个只有一个分区的表
  6. // 在生产上建表时建议根据数据特点预先分区
  7. admin.createTable(htd);
  8. // disable 表
  9. admin.disableTable(TableName.valueOf("tablename"));
  10. // truncate 表
  11. admin.truncateTable(TableName.valueOf("tablename"), true);
  12. // 删除表
  13. admin.deleteTable(TableName.valueOf("tablename"));
  14. }

DML操作

  
  1. //Table 为非线程安全对象,每个线程在对Table操作时,都必须从Connection中获取相应的Table对象
  2. try (Table table = connection.getTable(TableName.valueOf("tablename"))) {
  3. // 插入数据
  4. Put put = new Put(Bytes.toBytes("row"));
  5. put.addColumn(Bytes.toBytes("family"), Bytes.toBytes("qualifier"), Bytes.toBytes("value"));
  6. table.put(put);
  7. // 单行读取
  8. Get get = new Get(Bytes.toBytes("row"));
  9. Result res = table.get(get);
  10. // 删除一行数据
  11. Delete delete = new Delete(Bytes.toBytes("row"));
  12. table.delete(delete);
  13. // scan 范围数据
  14. Scan scan = new Scan(Bytes.toBytes("startRow"), Bytes.toBytes("endRow"));
  15. ResultScanner scanner = table.getScanner(scan);
  16. for (Result result : scanner) {
  17. // 处理查询结果result
  18. // ...
  19. }
  20. scanner.close();
  21. }

请关注公众号获取更多资料

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注