1. 程式人生 > >Hbase以api方式實現資料的插入和讀取

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資原始檔夾中。

整個工程截圖:


原始碼:

解壓過後,有兩個資料夾,只需要將root資料夾中的pom.xml檔案以Maven工程的方式匯入。