操作环境:

   java版本:    jdk 1.7以上

   hbase 版本:1.2.x

   hadoop版本:2.6.0以上

实现功能: 1,创建指定表

       2,删除指定表

      3,根据表名,行键,列族,列描述符,值插入数据

      4,根据指定表获取指定行键rowkey和列族family的数据 并以字符串的形式返回查询到的结果

      5,根据table查询表中的所有数据 无返回值,直接在控制台打印结果

      7,根据指定表获取指定行键rowKey和列族family的数据 并以Map集合的形式返回查询到的结果

      8,根据指定表获取指定行键rowKey的所有数据 并以Map集合的形式返回查询到的结果

      9,根据表名获取所有的数据

package com.hbase.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry; import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.RegexStringComparator;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.apache.hadoop.hbase.util.Bytes; public class HBaseUtil{ /**
* 连接池对象
*/
protected static Connection connection;
private static final String ZK_QUORUM = "hbase.zookeeper.quorum";
private static final String ZK_CLIENT_PORT = "hbase.zookeeper.property.clientPort";
/**
* HBase位置
*/
private static final String HBASE_POS = "192.168.1.104"; /**
* ZooKeeper位置
*/
private static final String ZK_POS = "localhost"; /**
* zookeeper服务端口
*/
private final static String ZK_PORT_VALUE = "2181"; /**
* 静态构造,在调用静态方法时前进行运行
* 初始化连接对象.
* */
static{
Configuration configuration = HBaseConfiguration.create();
configuration.set("hbase.rootdir", "hdfs://" + HBASE_POS
+ ":9000/hbase");
configuration.set(ZK_QUORUM, ZK_POS);
configuration.set(ZK_CLIENT_PORT, ZK_PORT_VALUE);
try {
connection = ConnectionFactory.createConnection(configuration);
} catch (IOException e) {
e.printStackTrace();
}// 创建连接池
}
/**
* 构造函数,用于初始化内置对象
*/
public HBaseUtil() {
Configuration configuration = HBaseConfiguration.create();
configuration.set("hbase.rootdir", "hdfs://" + HBASE_POS
+ ":9000/hbase");
configuration.set(ZK_QUORUM, ZK_POS);
configuration.set(ZK_CLIENT_PORT, ZK_PORT_VALUE);
try {
connection = ConnectionFactory.createConnection(configuration);
} catch (IOException e) {
e.printStackTrace();
}// 创建连接池
} /**
* @param tableName
* 创建一个表 tableName 指定的表名  seriesStr
* @param seriesStr
* 以字符串的形式指定表的列族,每个列族以逗号的形式隔开,(例如:"f1,f2"两个列族,分别为f1和f2)
**/
public boolean createTable(String tableName, String seriesStr) {
boolean isSuccess = false;// 判断是否创建成功!初始值为false
Admin admin = null;
TableName table = TableName.valueOf(tableName);
try {
admin = connection.getAdmin();
if (!admin.tableExists(table)) {
System.out.println("INFO:Hbase:: " + tableName + "原数据库中表不存在!开始创建...");
HTableDescriptor descriptor = new HTableDescriptor(table);
String[] series = seriesStr.split(",");
for (String s : series) {
descriptor.addFamily(new HColumnDescriptor(s.getBytes()));
}
admin.createTable(descriptor);
System.out.println("INFO:Hbase:: "+tableName + "新的" + tableName + "表创建成功!");
isSuccess = true;
} else {
System.out.println("INFO:Hbase:: 该表已经存在,不需要在创建!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(admin);
}
return isSuccess;
} /**
* 删除指定表名的表
* @param tableName  表名
* @throws IOException
* */
public boolean dropTable(String tableName) throws IOException {
boolean isSuccess = false;// 判断是否创建成功!初始值为false
Admin admin = null;
TableName table = TableName.valueOf(tableName);
try {
admin = connection.getAdmin();
if (admin.tableExists(table)) {
admin.disableTable(table);
admin.deleteTable(table);
isSuccess = true;
}
} finally {
IOUtils.closeQuietly(admin);
}
return isSuccess;
} /**
* 向指定表中插入数据
*
* @param tableName
* 要插入数据的表名
* @param rowkey
* 指定要插入数据的表的行键
* @param family
* 指定要插入数据的表的列族family
* @param qualifier
* 要插入数据的qualifier
* @param value
* 要插入数据的值value
* */
protected static void putDataH(String tableName, String rowkey, String family,
String qualifier, Object value) throws IOException {
Admin admin = null;
TableName tN = TableName.valueOf(tableName);
admin = connection.getAdmin();
if (admin.tableExists(tN)) {
try (Table table = connection.getTable(TableName.valueOf(tableName
.getBytes()))) {
Put put = new Put(rowkey.getBytes());
put.addColumn(family.getBytes(), qualifier.getBytes(),
value.toString().getBytes());
table.put(put);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("插入数据的表不存在,请指定正确的tableName ! ");
}
}
/**
* 根据指定表获取指定行键rowkey和列族family的数据 并以字符串的形式返回查询到的结果
*
* @param tableName
* 要获取表 tableName 的表名
* @param rowKey
* 指定要获取数据的行键
* @param family
* 指定要获取数据的列族元素
* @param qualifier
* 指定要获取数据的qualifier
*
* */
protected static String getValueBySeriesH(String tableName, String rowKey,
String family,String qualifier) throws IllegalArgumentException, IOException {
Table table = null;
String resultStr = null;
try {
table = connection
.getTable(TableName.valueOf(tableName.getBytes()));
Get get = new Get(Bytes.toBytes(rowKey));
if( !get.isCheckExistenceOnly()){
get.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
Result res = table.get(get);
byte[] result = res.getValue(Bytes.toBytes(family),
Bytes.toBytes(qualifier));
resultStr = Bytes.toString(result);
}else{
resultStr = null;
}
} finally {
IOUtils.closeQuietly(table);
}
return resultStr;
} /**
* 根据table查询表中的所有数据 无返回值,直接在控制台打印结果
* */
@SuppressWarnings("deprecation")
public void getValueByTable(String tableName) throws Exception {
Table table = null;
try {
table = connection.getTable(TableName.valueOf(tableName));
ResultScanner rs = table.getScanner(new Scan());
for (Result r : rs) {
System.out.println("获得到rowkey:" + new String(r.getRow()));
for (KeyValue keyValue : r.raw()) {
System.out.println("列:" + new String(keyValue.getFamily())
+ ":" + new String(keyValue.getQualifier())
+ "====值:" + new String(keyValue.getValue()));
}
}
} finally {
IOUtils.closeQuietly(table);
}
} /**
* 根据指定表获取指定行键rowKey和列族family的数据 并以Map集合的形式返回查询到的结果
*
* @param tableName
* 要获取表 tableName 的表名
* @param rowKey
* 指定的行键rowKey
* @param family
* 指定列族family
* */ protected static Map<String, String> getAllValueH(String tableName,
String rowKey, String family) throws IllegalArgumentException, IOException {
Table table = null;
Map<String, String> resultMap = null;
try {
table = connection.getTable(TableName.valueOf(tableName));
Get get = new Get(Bytes.toBytes(rowKey));
if(get.isCheckExistenceOnly()){
Result res = table.get(get);
Map<byte[], byte[]> result = res.getFamilyMap(family.getBytes());
Iterator<Entry<byte[], byte[]>> it = result.entrySet().iterator();
resultMap = new HashMap<String, String>();
while (it.hasNext()) {
Entry<byte[], byte[]> entry = it.next();
resultMap.put(Bytes.toString(entry.getKey()),
Bytes.toString(entry.getValue()));
}
}
} finally {
IOUtils.closeQuietly(table);
}
return resultMap;
} /**
* 根据指定表获取指定行键rowKey的所有数据 并以Map集合的形式返回查询到的结果
* 每条数据之间用&&&将Qualifier和Value进行区分
* @param tableName
* 要获取表 tableName 的表名
* @param rowkey
* 指定的行键rowKey
* */
public ArrayList<String> getFromRowkeyValues(String tableName, String rowkey){
Table table =null;
ArrayList<String> Resultlist = new ArrayList<>();
Get get = new Get(Bytes. toBytes ( rowkey ));
try {
table = connection.getTable(TableName.valueOf(tableName));
Result r = table.get(get);
for (Cell cell : r.rawCells()) {
//每条数据之间用&&&将Qualifier和Value进行区分
String reString = Bytes. toString (CellUtil. cloneQualifier (cell))+"&&&"+Bytes. toString (CellUtil. cloneValue (cell));
Resultlist.add(reString);
}
table.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return Resultlist;
}
/**
* 根据表名获取所有的数据
* */
@SuppressWarnings("unused")
private void getAllValues(String tableName){
try {
Table table= connection.getTable(TableName.valueOf(tableName));
Scan scan = new Scan();
ResultScanner resutScanner = table.getScanner(scan);
for(Result result: resutScanner){
System.out.println("scan: " + result);
}
} catch (IOException e) {
e.printStackTrace();
}
} public static void getTestDate(String tableName) throws IOException{
Table table = null;
table = connection.getTable(TableName.valueOf(tableName));
int count = 0;
Scan scan = new Scan();
scan.addFamily("f".getBytes()); Filter filter = new RowFilter(CompareFilter.CompareOp.EQUAL,
new RegexStringComparator("112213.*"));
scan.setFilter(filter);
ResultScanner resultScanner = table.getScanner(scan);
for(Result result : resultScanner){
System.out.println(result);
count++;
}
System.out.println("INFO:Hbase:: 测试结束!共有 " + count + "条数据");
} }

java实现hbase数据库的增删改查操作(新API)的更多相关文章

  1. 通过jdbc连接MySql数据库的增删改查操作

    一.获取数据库连接 要对MySql数据库内的数据进行增删改查等操作,首先要获取数据库连接 JDBC:Java中连接数据库方式 具体操作如下: 获取数据库连接的步骤: 1.先定义好四个参数 String ...

  2. PHP程序中使用PDO对象实现对数据库的增删改查操作的示例代码

    PHP程序中使用PDO对象实现对数据库的增删改查操作(PHP+smarty) dbconn.php <?php //------------------------使用PDO方式连接数据库文件- ...

  3. python web.py操作mysql数据库,实现对数据库的增删改查操作

    使用web.py框架,实现对mysql数据库的增删改查操作: 该示例代码中连接的是本地数据库testdb,user表,表结构比较简单,只有两个字段:mobile和passwd,类型均为字符型 实际应用 ...

  4. TP5.1:数据库的增删改查操作(基于面向对象操作)

    我们现实中对数据库的增删改查操作,都是使用模型类进行操作的(表名::),也就是面向对象操作,只有底层的代码用的是数据库操作(Db::table('表名')) 下面我将贴出模型类进行的增删改查操作,通过 ...

  5. TP5.1:数据库的增删改查操作(基于数据库操作)

    1.在app/index/controller文件夹下创建一个文件,名为:Operation 注意:起名一定要避开关键字,例如:mysql,curd等等,如果使用关键字起名,会造成报错! 在Opera ...

  6. greendao对SQLite数据库的增删改查操作

    利用greendao操作数据库时,都是以对象或者对象的list来进行增删改查的操作,操作的结果都是用一个list来接收的!!! 1.增加一条记录 Stu stu01=new Stu();stu01.s ...

  7. Django中ORM对数据库的增删改查操作

         前言 什么是ORM?  ORM(对象关系映射)指用面向对象的方法处理数据库中的创建表以及数据的增删改查等操作. 简而言之,就是将数据库的一张表当作一个类,数据库中的每一条记录当作一个对象.在 ...

  8. nodejs对mongodb数据库的增删改查操作(转载)

    首先要确保mongodb的正确安装,安装参照:http://docs.mongodb.org/manual/tutorial/install-mongodb-on-debian-or-ubuntu-l ...

  9. 69.nodejs对mongodb数据库的增删改查操作

    转自:https://www.cnblogs.com/sexintercourse/p/6485381.html 首先要确保mongodb的正确安装,安装参照:http://docs.mongodb. ...

随机推荐

  1. 什么是Service Mesh

    摘自https://zhuanlan.zhihu.com/p/61901608 Service Mesh作为下一代微服务技术的代名词,初出茅庐却深得人心一鸣惊人,大有一统微服务时代的趋势. 那么到底什 ...

  2. 美团关于分布式ID实践方案

    在复杂分布式系统中,往往需要对大量的数据和消息进行唯一标识.如在美团点评的金融.支付.餐饮.酒店.猫眼电影等产品的系统中,数据日渐增长,对数据分库分表后需要有一个唯一ID来标识一条数据或消息,数据库的 ...

  3. TurtleBot3使用课程-第一节b(北京智能佳)

    目录 1.模拟运行TurtleBot 2 1.1 ROS安装和设置2 1.1.1 turtlebot3 在Gazebo中模拟 3 1.1.1.1用于Gazebo的ROS包装 3 1.1.1.2 tur ...

  4. saltstack批量管理文件和计划任务

    简介 saltstack是由thomas Hatch于创建的一个开源项目,设计初衷是为了实现一个快速的远程执行系统.用来管理你的基础架构,可轻松管理成千上万台服务器. 关于saltstack更多功能本 ...

  5. ES6 class类 静态方法及类的继承

    一.class类 ES6之前都是定义函数以及函数的原型对象实现类型, 如果想要实现共享构造函数成员,可以用prototype来共享实现 ES6出现之后,使用class类的概念来实现原型的继承 二,静态 ...

  6. 在.NET Core中使用Channel(三)

    到目前为止,我们一直在使用所谓的"Unbounded"通道.你会注意到,当我们创建通道时,我们这样做: var myChannel = Channel.CreateUnbounde ...

  7. 音视频入门-19-使用giflib处理GIF图片

    * 音视频入门文章目录 * GIFLIB The GIFLIB project 上一篇 [手动生成一张GIF图片], 自己生成了一张 GIF 动态图 rainbow.gif. 下面,使用 GIFLIB ...

  8. Linux下最常用的10个文件压缩工具

    作者简介 李先生(Lemon),高级运维工程师(自称),SRE专家(目标),梦想在35岁买一辆保时捷.喜欢钻研底层技术,认为底层基础才是王道.一切新技术都离不开操作系统(CPU.内存.磁盘).网络等. ...

  9. yolov5实战之皮卡丘检测

    前言 从接触深度学习开始一直都做的是人脸识别,基本上也一直都在用mxnet. 记得之前在刚接触的时候看到博客中写到,深度学习分三个层次,第一个层次是分类,第二个层次是检测,第三个层次是分割.人脸识别算 ...

  10. 剑指offer 面试题0:高质的代码:即考虑边界条件、特殊输入和错误处理

    Q:把一个字符串转换为整数. A1:一个普通但漏洞百出的解法. int StrToInt(char* str) { int number = 0; while (*str != 0) { number ...