HBase java API实践

HBase java API实践

依赖

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();

    }
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值