intellij創建hbase工程


打開intellj

創建一個hbase Module模塊

 右擊Add_FrameWork_Support添加Maven依賴

添加hbase的client包依賴,client的版本需要與實際的hbase版本一致。之后IDEA將會自動下載依賴包,可以在External Libraries中查看下載的依賴包。

<dependencies>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>1.2.1</version>
        </dependency>                  
</dependencies>

等依賴下載好之后,在src/main/resources目錄下新建一個hbase-site.xml文件,把hbase集群的配置文件內容粘貼過去。

在src/test/java目錄下新建一個java文件:

package com.yzd.hbase;

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 org.junit.Test;

import java.io.IOException;

public class test {
    @Test
    public void put() throws Exception{
        //  創建conf對象
        Configuration configuration = HBaseConfiguration.create();
        //  通過連接工廠創建連接對象
        Connection conn = ConnectionFactory.createConnection(configuration);
        //  通過連接查詢table對象
        TableName tname = TableName.valueOf("ns1:t1");
        //  獲得表
        Table table = conn.getTable(tname);

        // 通過bytes類創建字節數組
        byte[] rowid = Bytes.toBytes("row3");
        //  創建put對象
        Put put = new Put(rowid);
        put.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("id"), Bytes.toBytes(120));
        put.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("name"),Bytes.toBytes("lucy"));
        put.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("age"),Bytes.toBytes(20));
        put.addColumn(Bytes.toBytes("f2"),Bytes.toBytes("hobby"),Bytes.toBytes("reading_books"));
        put.addColumn(Bytes.toBytes("f2"),Bytes.toBytes("addr"),Bytes.toBytes("Beijing"));

        table.put(put);
        System.out.println("插入成功");
    }

    /*  查詢數據  */
    @Test
    public void testGet() throws IOException {
        //  創建conf對象
        Configuration conf = HBaseConfiguration.create();
        //  通過連接工廠創建連接對象
        Connection conn = ConnectionFactory.createConnection(conf);
        //  創建TableName對象
        TableName tname = TableName.valueOf("ns1:t1");
        //  傳入TableName對象獲取表
        Table table = conn.getTable(tname);
        //  new一個get對象,傳入rowkey
        Get get = new Get(Bytes.toBytes("row3"));

        //  獲取數據,傳入get對象
        Result result = table.get(get);

        byte[] id_value = result.getValue(Bytes.toBytes("f1"),Bytes.toBytes("id"));
        System.out.println(Bytes.toInt(id_value));
    }
}

然后運行testGet方法,輸出如下信息:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM