目录

  • 准备工作
    • 创建maven项目
    • 添加依赖
  • API操作
    • 创建HBase连接
    • 创建HBase表
    • 删除表
    • 向表中插入数据
    • 查看数据
    • 过滤器操作
  • 全部代码
    • 注意事项

准备工作

创建maven项目

添加依赖

在pom.xml文件中加入

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.learn.test</groupId><artifactId>HBase</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.apache.hbase</groupId><artifactId>hbase-client</artifactId><version>2.4.1</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.testng</groupId><artifactId>testng</artifactId><version>6.14.2</version><scope>test</scope></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.6</version></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.1</version><configuration><target>1.8</target><source>1.8</source></configuration></plugin></plugins></build>
</project>

等待它安装

完成状态

在resource下创建log文件,便于查看错误

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

API操作

所需要的包

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;import java.io.IOException;
import java.util.List;

创建HBase连接

我所用的Hadoop集群是HA集群,主节点不一定是active状态,所以IP地址得相应的改动

  @BeforeTestpublic void beforeTest() throws IOException {//        1.创建hbase配置Configuration configuration = HBaseConfiguration.create();configuration.set("hbase.zookeeper.quorum", "192.168.237.146");configuration.set("hbase.zookeeper.property.clientPort", "2181");
//        2.创建hbase的连接connection = ConnectionFactory.createConnection(configuration);
//        3.创建admin的连接admin = connection.getAdmin();}

创建HBase表

在创建表之前都得先判断该表是否存在

 @Testpublic void createTableTest() throws IOException {//        1.判断表是否存在TableName tableName = TableName.valueOf("water_bill");if (admin.tableExists(tableName)) {return;}
//        2.构建表描述构建器(构建器设计模式)TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tableName);
//        3.构建列族描述构建器ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("info"));
//        4.构建表构建器和列族描述构建器建立联系ColumnFamilyDescriptor columnFamilyDescriptor = columnFamilyDescriptorBuilder.build();tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptor);
//        5.创建表TableDescriptor tableDescriptor = tableDescriptorBuilder.build();admin.createTable(tableDescriptor);}


删除表

 @Testpublic void deleteTableTest() throws IOException {//        1.确认表是否存在TableName tableName = TableName.valueOf("water_bill");if (admin.tableExists(tableName)) {//            禁用表admin.disableTable(tableName);
//            删除表admin.deleteTable(tableName);}}


向表中插入数据

    @Testpublic void putTableTest() throws IOException {//        1.使用hbase连接获取表TableName tableName = TableName.valueOf("water_bill");Table table = connection.getTable(tableName);
//        2.构建rowkey,列簇名,列名
//        3.构建put对象Put put = new Put(Bytes.toBytes("4944191"));
//        4.添加姓名列put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes("张三"));
//        5.使用表执行put操作table.put(put);
//        6.关闭表对象table.close();}

查看数据

    @Testpublic void getableTest() throws IOException {//        1、使用hbase连接获取表TableName tableName = TableName.valueOf("water_bill");Table table = connection.getTable(tableName);
//        2、构建rowkey、列簇名、列名
//        3、构建get对象Get get = new Get(Bytes.toBytes("4944191"));
//        4、执行get请求,获取result对象Result result = table.get(get);
//        5、获取所有的单元格List<Cell> cellList = result.listCells();for (Cell cell : cellList) {//          获取单元格的列簇名String cf = Bytes.toString(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength());
//          获取单元格的列名String cn = Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
//          获取单元格的值String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());System.out.println(cf + ":" + cn + "->" + value);}
//        6、关闭表对象table.close();}


过滤器操作

数据得自己创建,用之前的插入命令多操作几次就行

    @Testpublic void scanFilterTest() throws IOException {//        1.判断表是否存在Table table = connection.getTable(tableName);
//        2.构建scanFilter对象Scan scan = new Scan();
//        3.构建过滤器,需要构建两个日期范围的过滤器
//        开始日期SingleColumnValueFilter startFilter = new SingleColumnValueFilter(Bytes.toBytes("info"),//列族Bytes.toBytes("record_date"),//列名CompareOperator.GREATER_OR_EQUAL,//比较器new BinaryComparator(Bytes.toBytes("2020-06-01"))//比较表达式);
//          结束日期过滤器SingleColumnValueFilter endFilter = new SingleColumnValueFilter(Bytes.toBytes("info"),//列族Bytes.toBytes("record_date"),//列名CompareOperator.LESS_OR_EQUAL,//比较器new BinaryComparator(Bytes.toBytes("2020-06-31"))//比较表达式);
//        4.构建过滤器列表FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL,//and操作startFilter,endFilter);//        5.设置scan扫描器的过滤器scan.setFilter(filterList);
//        6.通过表的执行结果ResultScanner resultScanner = table.getScanner(scan);
//        7.通过执行结果获取迭代器Iterator<Result> resultIterator = resultScanner.iterator();
//        8.迭代打印resultwhile (resultIterator.hasNext()){Result result = resultIterator.next();//获取resultbyte[] rowkey = result.getRow();System.out.println("rowkey->" +Bytes.toString(rowkey));
//        5、获取所有的单元格List<Cell> cellList = result.listCells();for (Cell cell : cellList) {//          获取单元格的列簇名String cf = Bytes.toString(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength());
//          获取单元格的列名String cn = Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
//          获取单元格的值String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());System.out.println(cf + ":" + cn + "->" + value);}System.out.println("===============================================");}
//        9.关闭resultScanner.close();table.close();}

查询六月的数据

全部代码

package cn.lenar.hbase;import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;import java.io.IOException;
import java.util.List;/*** @author 公羽* @time : 2021/4/11 15:02* @File : HBase_test.java*/
public class HBase_test {private Connection connection;private Admin admin;@BeforeTestpublic void beforeTest() throws IOException {//        1.创建hbase配置Configuration configuration = HBaseConfiguration.create();configuration.set("hbase.zookeeper.quorum", "192.168.237.146");configuration.set("hbase.zookeeper.property.clientPort", "2181");//        2.创建hbase的连接connection = ConnectionFactory.createConnection(configuration);
//        3.创建admin的连接admin = connection.getAdmin();}//        测试创建表@Testpublic void createTableTest() throws IOException {//        1.判断表是否存在TableName tableName = TableName.valueOf("water_bill");if (admin.tableExists(tableName)) {return;}
//        2.构建表描述构建器(构建器设计模式)TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tableName);
//        3.构建列族描述构建器ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("info"));
//        4.构建表构建器和列族描述构建器建立联系ColumnFamilyDescriptor columnFamilyDescriptor = columnFamilyDescriptorBuilder.build();tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptor);
//        5.创建表TableDescriptor tableDescriptor = tableDescriptorBuilder.build();admin.createTable(tableDescriptor);}//       测试删除表@Testpublic void deleteTableTest() throws IOException {//        1.确认表是否存在TableName tableName = TableName.valueOf("water_bill");if (admin.tableExists(tableName)) {//            禁用表admin.disableTable(tableName);
//            删除表admin.deleteTable(tableName);}}//    测试插入数据@Testpublic void putTableTest() throws IOException {//        1.使用hbase连接获取表TableName tableName = TableName.valueOf("water_bill");Table table = connection.getTable(tableName);
//        2.构建rowkey,列簇名,列名
//        3.构建put对象Put put = new Put(Bytes.toBytes("4944191"));
//        4.添加姓名列put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes("张三"));
//        5.使用表执行put操作table.put(put);
//        6.关闭表对象table.close();}//测试查看数据@Testpublic void getableTest() throws IOException {//        1、使用hbase连接获取表TableName tableName = TableName.valueOf("water_bill");Table table = connection.getTable(tableName);
//        2、构建rowkey、列簇名、列名
//        3、构建get对象Get get = new Get(Bytes.toBytes("4944191"));
//        4、执行get请求,获取result对象Result result = table.get(get);
//        5、获取所有的单元格List<Cell> cellList = result.listCells();for (Cell cell : cellList) {//          获取单元格的列簇名String cf = Bytes.toString(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength());
//          获取单元格的列名String cn = Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
//          获取单元格的值String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());System.out.println(cf + ":" + cn + "->" + value);}
//        6、关闭表对象table.close();}@Testpublic void scanFilterTest() throws IOException {//        1.判断表是否存在Table table = connection.getTable(tableName);
//        2.构建scanFilter对象Scan scan = new Scan();
//        3.构建过滤器,需要构建两个日期范围的过滤器
//        开始日期SingleColumnValueFilter startFilter = new SingleColumnValueFilter(Bytes.toBytes("info"),//列族Bytes.toBytes("record_date"),//列名CompareOperator.GREATER_OR_EQUAL,//比较器new BinaryComparator(Bytes.toBytes("2020-06-01"))//比较表达式);
//          结束日期过滤器SingleColumnValueFilter endFilter = new SingleColumnValueFilter(Bytes.toBytes("info"),//列族Bytes.toBytes("record_date"),//列名CompareOperator.LESS_OR_EQUAL,//比较器new BinaryComparator(Bytes.toBytes("2020-06-31"))//比较表达式);
//        4.构建过滤器列表FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL,//and操作startFilter,endFilter);//        5.设置scan扫描器的过滤器scan.setFilter(filterList);
//        6.通过表的执行结果ResultScanner resultScanner = table.getScanner(scan);
//        7.通过执行结果获取迭代器Iterator<Result> resultIterator = resultScanner.iterator();
//        8.迭代打印resultwhile (resultIterator.hasNext()){Result result = resultIterator.next();//获取resultbyte[] rowkey = result.getRow();System.out.println("rowkey->" +Bytes.toString(rowkey));
//        5、获取所有的单元格List<Cell> cellList = result.listCells();for (Cell cell : cellList) {//          获取单元格的列簇名String cf = Bytes.toString(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength());
//          获取单元格的列名String cn = Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
//          获取单元格的值String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());System.out.println(cf + ":" + cn + "->" + value);}System.out.println("===============================================");}
//        9.关闭resultScanner.close();table.close();}@AfterTestpublic void afterTest() throws IOException {//        4.关闭adminadmin.close();connection.close();}
}

注意事项

遇到的延时问题的解决办法
得在windows中C:\Windows\System32\drivers\etc下加入IP映射

HBase学习(四) HBase API操作相关推荐

  1. Hbase教程(四) Hbase数据库JavaAPI接口

    Hbase教程(四) Hbase数据库JavaAPI接口 Hbase是一个分布式的.面向列的开源数据库,HDFS文件操作常有两种方式,一种是命令行方式,即Hbase提供了一套与Linux文件命令类似的 ...

  2. Tensorflow学习四---高阶操作

    Tensorflow学习四-高阶操作 Merge and split 1.tf.concat 拼接 a = tf.ones([4,32,8]) b = tf.ones([2,32,8]) print( ...

  3. MVC3学习 四 EF删除操作

    由于EF的框架是4.1的,所以现在如果想更新部分字段的话,只能从数据库中查出一次数据(不用查的方法还没找到,需要继续研究),不能像5.1的版本可以不用查. 更新的Action需要用到[HttpGet] ...

  4. 【HBase学习笔记-尚硅谷-Java API shell命令 谷粒微博案例】

    HBase学习笔记 HBase 一.HBase简介 1.HBase介绍 2.HBase的逻辑结构和物理结构 3.数据模型 4.基本架构 二.快速入门 1.配置HBase 2.命令 三.API 1.获取 ...

  5. Hbase 完全分布式模式的搭建、命令行操作、Java API操作

    追风赶月莫停留,平芜尽处是春山. 文章目录 追风赶月莫停留,平芜尽处是春山. 环境 Hbase 完全分布式模式的搭建 一.下载安装包,解压到合适位置: 二.配置相关的文件: 三.将Hbase复制到其他 ...

  6. HBase学习01--Hbase的安装

    HBase学习01–Hbase的安装 一.单机模式: 1.1 解压软件包 tar -zxvf hbase-1.1.3-bin.tar.gz 1.2 配置JAVA_HOME环境变量 cd /usr/lo ...

  7. 2021年大数据HBase(四):HBase的相关操作-客户端命令式!【建议收藏】

    全网最详细的大数据HBase文章系列,强烈建议收藏加关注! 新文章都已经列出历史文章目录,帮助大家回顾前面的知识重点. 目录 系列历史文章 前言 HBase的相关操作-客户端命令式 1.进入HBase ...

  8. HBase 6、用Phoenix Java api操作HBase

    开发环境准备:eclipse3.5.jdk1.7.window8.hadoop2.2.0.hbase0.98.0.2.phoenix4.3.0 1.从集群拷贝以下文件:core-site.xml.hb ...

  9. 使用 Java API 操作 HBase

    使用 Java API 操作 HBase 数据库,就类似HBase Shell,本质上一个是Java 代码,一个是Shell 命令.(hadoop 的文件系统莫不如此,可用Java API 的方式操作 ...

最新文章

  1. linux启动tomcat不停的触发gc,tomcat的rmi触发的full gc的时间过长的优化
  2. 高并发-【抢红包案例】之三:使用乐观锁方式修复红包超发的bug
  3. mysql1756_MySQL Error_code: 1756
  4. springboot中controller单例模式多线程安全的简单理解
  5. FatFsVersion0.01源码分析
  6. The Best Vacation CodeForces - 1358D(贪心+尺取)
  7. js初步简单的编程代码
  8. 推荐系统遇上深度学习(二)--FFM模型理论和实践
  9. Android TextView滚动的两种方案
  10. [BZOJ1492][NOI2007]货币兑换Cash(斜率优化+CDQ分治)
  11. 南阳理工acm1043高数
  12. Sql Server2008R2的完全卸载及重新安装
  13. android ui设计 面试问题,2019新版UI设计面试题汇总附答案
  14. 电脑硬盘分区太多?如何合并分区?
  15. Thinkpad E450c进入BIOS
  16. 合振动的初相位推导_两个同方向、同频率的简谐振动表达式为和,试求它们的合振动的振幅和初相位。...
  17. cacheable 表达式,多个方法参数的@Cacheable键
  18. 关于电脑磁盘满了爆红解决方法之一
  19. 大数据最佳实践-hbase
  20. 程序员应了解:知识技能金字塔

热门文章

  1. c语言如何反复执行一段程序,C语言中重复执行程序的问题
  2. linux 开启rsh权限,开启rsh服务
  3. 考华为HCIP证书多钱?
  4. 程序员应当正确突破英语障碍
  5. Java进阶之路~适配器设计模式amp;字符串方法
  6. 据说一个人的标准体重应该是其身高(单位:厘米)减去100、再乘以0.9所得到的公斤数。已知市斤的数值是公斤数值的两倍。现给定某人身高,请你计算其标准体重应该是多少?(顺便也悄悄给自己算一下吧……)
  7. Python-OpenCV——Image Blurring(Image Smoothing)
  8. UART串口通信软件推荐
  9. Android之常见事件响应的实现方式
  10. ARM32 寄存器分类