用的maven依赖:
org.apache.hbase
hbase-client
2.1.7
package com.imti.hbase;
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.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class HbaseInfo {
public static void main(String[] args) throws IOException {
//zookeeper配置
Configuration config = HBaseConfiguration.create();
//在HBase中config中 hbase-site.xml中关于zookeeper的配置
config.set("hbase.zookeeper.quorum","192.168.40.2,192.168.40.4");
config.set("hbase.zookeeper.property.clientPort","2181");
//HADOOP集群配置
Connection connection= ConnectionFactory.createConnection(config);
HBaseAdmin admin = (HBaseAdmin) connection.getAdmin();
//获取集群中所有表名 相当于在HBase中的 list 命令;
TableName[] table= admin.listTableNames();
for (TableName tableName:table ){
System.out.println(tableName.getNameAsString());
}
// 建表
// :1.定义表名
TableDescriptorBuilder studentabletname = TableDescriptorBuilder.newBuilder(TableName.valueOf("Student"));
//2.定义定义列族
ColumnFamilyDescriptor stidentinfo = ColumnFamilyDescriptorBuilder.of("stidentinfo");
//3.关联列族和表名
studentabletname.setColumnFamily(stidentinfo);
//4.构建表的模型
TableDescriptor build = studentabletname.build();
admin.createTable(build);
//在创建好的表中添加单条或多条记录
Table student = connection.getTable(TableName.valueOf("Student"));
//将一个rowkey(行键)字符串转换为字节数组
Put put =new Put(Bytes.toBytes("20210108a"));
//将要插入的列族,列名,数据都定义出来
put.addColumn(Bytes.toBytes("stidentinfo"),Bytes.toBytes("Studentnames"),Bytes.toBytes("wangwu"));
put.addColumn(Bytes.toBytes("stidentinfo"),Bytes.toBytes("Studentname"),Bytes.toBytes("王五"));
student.put(put);
//实现批量插入(因为是往表里插入所以表要放在外边,其中rowkey,)
List<Put> list =new ArrayList<>();
for (int i = 0; i < 10000; i++) {
Put puts =new Put(Bytes.toBytes("20210108a"+i));
puts.addColumn(Bytes.toBytes("stidentinfo"),Bytes.toBytes("Studentage"),Bytes.toBytes(Integer.toString(i)));
puts.addColumn(Bytes.toBytes("stidentinfo"),Bytes.toBytes("Studentsex"),Bytes.toBytes("123xxxxxx"+i));
list.add(puts);
}
student.put(list);
//批量导入后一般是要关闭资源的,防止资源浪费
/* connection.close();
admin.close();*/
//用命令scan扫描表取数据
Scan sacn=new Scan();
//返回的是一个个迭代器,所有用while循环取
ResultScanner scanner = student.getScanner(sacn);
Result res;
while((res=scanner.next())!=null){
List<Cell> cells = res.listCells();
for (Cell value:cells) {
//将行键,列族,列,值通过克隆方式出来,出来是地址,要BytestoString转换成字符
System.out.println("rowkey值:"+Bytes.toString(CellUtil.cloneRow(value))+"列族:"+Bytes.toString(CellUtil.cloneFamily(value))+"列名:"+Bytes.toString(CellUtil.cloneQualifier(value))+"值:"+Bytes.toString(CellUtil.cloneValue(value)));
}
}
}
}
如有不足,请多见谅 -_-||