Hadoop-06-使用Eclipse开发HBase程序,hadoop-06-hbase


使用Eclipse开发HBase程序的配置步骤

 

1.新建一个普通的java project.

2.在项目的 属性--java build path--libraries--Add External Jars,添加hadoop安装目录下的hbase-0.90.5.jarhbase-0.90.5-tests.jar,以及hbase安装目录下的lib目录下的所有jar文件。

3.在项目根目录下新建conf目录,然后拷贝hbase安装目录下的conf目录下的hbase-site.xml到该文件夹下。

4.在项目的 属性--java build path--libraries--Add class folder,将刚刚新建的conf目录添加进去。至此,开发环境搭建完成。

5.新建一个java类,添加如下代码:

package com.hadoop.hbase.test;

 

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.hbase.HBaseConfiguration;

import org.apache.hadoop.hbase.HColumnDescriptor;

import org.apache.hadoop.hbase.HTableDescriptor;

import org.apache.hadoop.hbase.client.Get;

import org.apache.hadoop.hbase.client.HBaseAdmin;

import org.apache.hadoop.hbase.client.HTable;

import org.apache.hadoop.hbase.client.Put;

import org.apache.hadoop.hbase.client.Result;

import org.apache.hadoop.hbase.client.ResultScanner;

import org.apache.hadoop.hbase.client.Scan;

import org.apache.hadoop.hbase.util.Bytes;

 

public class HbaseTest {

 

public static void main(String[] args) throws Exception {

 

Configuration config = HBaseConfiguration.create();

 

// create table

HBaseAdmin admin = new HBaseAdmin(config);

HTableDescriptor htd = new HTableDescriptor("student");

HColumnDescriptor hcd = new HColumnDescriptor("address");

HColumnDescriptor hcd2 = new HColumnDescriptor("info");

htd.addFamily(hcd);

htd.addFamily(hcd2);

admin.createTable(htd);

byte[] tableName = htd.getName();

HTableDescriptor[] tables = admin.listTables();

if (tables.length != 1 && Bytes.equals(tableName, tables[0].getName())) {

throw new Exception("Failed create table !!!");

}

 

// run some operations--a put, a get, a scan --against the table

HTable table = new HTable(config, tableName);

byte[] row1 = Bytes.toBytes("John");

Put p1 = new Put(row1);

byte[] databytes = Bytes.toBytes("address");

p1.add(databytes, Bytes.toBytes("city"), Bytes.toBytes("WuHan"));

p1.add(databytes, Bytes.toBytes("province"), Bytes.toBytes("HuBei"));

table.put(p1);

 

Get g = new Get(row1);

Result result = table.get(g);

System.out.println("Result: " + result);

 

Scan scan = new Scan();

ResultScanner scanner = table.getScanner(scan);

for (Result scannerResult : scanner) {

System.out.println("Scan: " + scannerResult);

}

 

// drop the table

// admin.disableTable(tableName);

// admin.deleteTable(tableName);

System.out.println("----done----");

 

}

 

}

6.进入hbase shell,使用 list命令即可以看见新建的表,使用scan student’ 即可以看见插入的数据。

 

至此,第一个hbase程序开发完成。

 

 

相关内容

    暂无相关文章