Hbase以api方式实现数据的插入和读取

测试环境:Hadoop-2.7.3集群,HBase-1.3.0,Idea2018(Linux版)

这里是对已经存在的表t1进行put与get操作。

代码:

package com.test;

import org.apache.hadoop.conf.Configuration;
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;

/**
 * @Author zhang
 * @Date 18-6-5 下午1:54
 */
public class HbaseDemo {

    public static void main(String[] args) throws IOException {
        //put();
        String val=get();
        System.out.println(val);
    }

    public static void put() throws IOException {
        //创建conf对象
        Configuration configuration=HBaseConfiguration.create();
        //创建连接
        Connection  connection= ConnectionFactory.createConnection(configuration);
        //获取表t1
        TableName tname=TableName.valueOf("ns1:t1");
        //获取Table
        Table table=connection.getTable(tname);
        //通过bytes工具创建字节数组
        byte[] rowid=Bytes.toBytes("row1");
        //创建put对象
        Put put=new Put(rowid);
        //列族
        byte[] f1=Bytes.toBytes("f1");
        //列
        byte[] col=Bytes.toBytes("name");
        //值
        byte[] val=Bytes.toBytes("李四");
        //添加列
        put.addColumn(f1,col,val);
        //执行添加任务
        table.put(put);
    }

    public static String get() throws IOException {
        //创建conf对象
        Configuration configuration=HBaseConfiguration.create();
        //创建连接
        Connection  connection= ConnectionFactory.createConnection(configuration);
        //获取表t1
        TableName tname=TableName.valueOf("ns1:t1");
        //获取Table
        Table table=connection.getTable(tname);
        //通过bytes工具创建字节数组
        byte[] rowid=Bytes.toBytes("row1");
        //创建get对象
        Get get=new Get(rowid);
        Result r=table.get(get);
        byte[] bytes=r.getValue(Bytes.toBytes("f1"),Bytes.toBytes("name"));
        return Bytes.toString(bytes);
    }
}

同时将hbase-site.xml放到resources资源文件夹中。

整个工程截图:


源代码:

点此下载源代码:hbase-put-get.zip

解压过后,有两个文件夹,只需要将root文件夹中的pom.xml文件以Maven工程的方式导入。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值