依赖
hbase选择0.94.10版本,hadoop-common选择0.22.0版本,两个依赖包版本要适配,其他版本可能存在兼容问题
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase</artifactId>
<version>0.94.10</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>0.22.0</version>
</dependency>
动手实践
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
public class HbaseOperator {
public static void main(String[] args) throws IOException {
//hbaseClient配置实例
Configuration config = HBaseConfiguration.create();
config.set("hbase.zookeeper.quorum","127.0.0.1");
config.set("hbase.zookeeper.property.clientPort","2181");
//创建HTable实例,连接到hbase,使用完后要关闭
HTable htable = new HTable(config,Bytes.toBytes("test"));
//创建一个Get实例,入参为主键,用于htable实例向hbase发送一个get请求
Get get = new Get(Bytes.toBytes("111"));
get.setMaxVersions(1);
//发起get请求,并打印请求结果
Result result = htable.get(get);
System.out.println(Bytes.toString(result.value()));
//全表扫描,大表慎用
Scan scan = new Scan();
ResultScanner resultScanner =htable.getScanner(scan);
while(true){
Result res = resultScanner.next();
if(res!=null){
System.out.println("key: " + Bytes.toString(res.getRow()));
System.out.println("value: "+Bytes.toString(res.value()));
} else{
break;
}
}
//操作完毕,关闭连接
htable.close();
//HBaseAdmin类实例用于操作表,例如:新建、删除、disable、enable等
HBaseAdmin hBaseAdmin = new HBaseAdmin(config);
//获取表的describe信息,修改表名,并新建一个结构相同的表
HTableDescriptor hTableDescriptor = hBaseAdmin.getTableDescriptor(Bytes.toBytes("t1"));
hTableDescriptor.setName(Bytes.toBytes("t2"));
hBaseAdmin.createTable(hTableDescriptor);
//删除一个表,先disable再delete
hBaseAdmin.disableTable(Bytes.toBytes("t1"));
hBaseAdmin.deleteTable(Bytes.toBytes("t1"));
System.out.println(hTableDescriptor.getNameAsString());
//操作完毕后关闭连接
hBaseAdmin.close();
}
}