1. 程式人生 > >學習筆記:從0開始學習大資料-7.hbase java程式設計hello world

學習筆記:從0開始學習大資料-7.hbase java程式設計hello world

上節搭建了hbase啟動環境,本節搭建hbase程式設計環境

1. 準備測試資料,建立表student

#hbase shell

create 'student','info','address'
put 'student','1','info:age','20'
put 'student','1','info:name','linbin'
put 'student','1','info:class','1'
put 'student','1','address:city','guangzhou'
put 'student','1','address:area','baiyun zone'
put 'student','2','info:age','21'
put 'student','2','info:name','yangdandan'
put 'student','2','info:class','1'
put 'student','2','address:city','beijing'
put 'student','2','address:area','CBD'
scan 'student'

2. Eclipse 建立hbase專案

檔案-》新建-》專案-》maven project->輸入專案名-》完成

3.修改專案下的pom.xml  增加

    <dependency>
        <groupId>org.apache.hbase</groupId>
        <artifactId>hbase-it</artifactId>
        <version>1.2.0</version>
    </dependency>

儲存後等待自動下載相關jar檔案

4. 修改 App.java 檔案

package com.linbin.hbase;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

public class App 
{
	private static Configuration config = null;
	private static Connection connection = null;
	private static Table table = null;
    public static void main( String[] args ) throws Exception
    {
		config = HBaseConfiguration.create();
		config.set("hbase.zookeeper.quorum", "centos7");    //指定伺服器
		connection = ConnectionFactory.createConnection(config);
		table = connection.getTable(TableName.valueOf("student"));  //開啟student表
		queryData();
		table.close();
		connection.close();
    }
    
	public static void queryData() throws IOException {
		Get get = new Get(Bytes.toBytes("2"));    //獲取表的行key
		Result result = table.get(get);
		System.out.println(Bytes.toString(result.getValue(Bytes.toBytes("info"), Bytes.toBytes("name"))));   //輸出 info:name列
		System.out.println(Bytes.toString(result.getValue(Bytes.toBytes("info"), Bytes.toBytes("age"))));    //輸出  info:age列
	}
}

簡單的連線hbase資料庫,開啟表,查詢指定行,列印指定列,關閉表和連線。

5. 測試執行,注意執行時 Run as -> Java application    這個不是web專案,是java應用程式專案

正常執行,顯示查詢的結果

6. 程式設計實現hbase表的增刪改查java api 參見:

https://blog.csdn.net/u014695188/article/details/73188668   hbase程式設計:通過Java api操作hbase