Hbase 2.2.2 简单API操作
前言
小案例中有创建表、创建命名空间、插入数据、获取数据。
环境准备
maven依赖可根据自己的版本进行调整
<!-- hbase依赖-->
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-server</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-auth</artifactId>
<version>3.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-common</artifactId>
<version>2.2.2</version>
</dependency>
小案例
代码:
package com.hbase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
public class TestHbaseApi {
public static void main(String[] args) throws IOException {
Connection conn = getConn();
Admin admin = conn.getAdmin();
try {
NamespaceDescriptor aDefault = admin.getNamespaceDescriptor("default");
}catch (NamespaceNotFoundException e){
//没有命名空间,创建命名空间
admin.createNamespace(NamespaceDescriptor.create("default").build());
}
System.out.println("命名空间存在.");
//判断表是否存在
TableName tableName = TableName.valueOf("student");
boolean exists = admin.tableExists(tableName);
if (exists){
//获取表对象
Table table = conn.getTable(tableName);
//获取数据
Result result = table.get(new Get(Bytes.toBytes("1001")));
if (result.isEmpty()){
//如果没有数据则新增
Put put = new Put(Bytes.toBytes("1001"));
String family = "info";
String qualifier = "name";
String value = "zhangsan";
put.addColumn(Bytes.toBytes(family),Bytes.toBytes(qualifier),Bytes.toBytes(value));
table.put(put);
System.out.println("数据新增");
}else {
//有数据就展示
Cell[] cells = result.rawCells();
for (Cell cell : cells) {
System.out.println("family:" + Bytes.toString(CellUtil.cloneFamily(cell)));
System.out.println("qualifier:" + Bytes.toString(CellUtil.cloneQualifier(cell)));
System.out.println("row:" + Bytes.toString(CellUtil.cloneRow(cell)));
System.out.println("value:" + Bytes.toString(CellUtil.cloneValue(cell)));
}
}
}else {
//表不存在
//表描述建造者
TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(tableName);
//列族描述建造者
ColumnFamilyDescriptorBuilder cfdb = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("info"));
//设置最大版本号
cfdb.setMaxVersions(3);
//创建列族描述
ColumnFamilyDescriptor familyDescriptor = cfdb.build();
//将列族加入到表描述中
builder.setColumnFamily(familyDescriptor);
//创建表描述
TableDescriptor tableDescriptor = builder.build();
//创建表
admin.createTable(tableDescriptor);
System.out.println("表创建成功");
}
}
public static Connection getConn() throws IOException {
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum","hadoop100,hadoop101,hadoop102");
conf.set("hbase.zookeeper.property.clientPort", "2181");
Connection connection = ConnectionFactory.createConnection(conf);
return connection;
}
}