现在的位置: 首页 > 综合 > 正文

HBase客户端程序

2013年09月20日 ⁄ 综合 ⁄ 共 2179字 ⁄ 字号 评论关闭
import java.io.IOException;

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.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
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 ExampleClient {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws MasterNotRunningException 
	 */
	public static void main(String[] args) throws MasterNotRunningException, IOException {
		// TODO Auto-generated method stub
		Configuration config = HBaseConfiguration.create();
		
		//Create table
		HBaseAdmin admin = new HBaseAdmin(config);
		HTableDescriptor htd = new HTableDescriptor("test"); // 要创建的表的名称
		HColumnDescriptor hcd = new HColumnDescriptor("profile"); // 创建一个列族
		htd.addFamily(hcd);
		admin.createTable(htd);
		
		byte[] tablename = htd.getName(); // HBase Table Descriptor
		HTableDescriptor[] tables = admin.listTables();
		System.out.println(tables.length);
		if(tables.length != 1 && Bytes.equals(tablename, tables[0].getName()))
			throw new IOException("Failed create of table");
		
		HTable table = new HTable(config, tablename);
		byte[] row1 = Bytes.toBytes("88888888");
		Put p1 = new Put(row1); // Create a Put operation for the specified row.
		byte[] profile = Bytes.toBytes("profile");
		p1.add(profile, Bytes.toBytes("gender"), Bytes.toBytes("male"));
		table.put(p1); // 存储
		Get g1 = new Get(row1);
		Result result = table.get(g1);
		System.out.println("Get: " + result);
		Scan scan = new Scan();
		ResultScanner scanner = table.getScanner(scan);
		try{
			for(Result scannerResult : scanner){
				System.out.println("Scan: " + scannerResult);
			}
		}finally{
			scanner.close();
		}
		
		// admin.disableTable(tablename);
		// admin.deleteTable(tablename);
	}

}

HTableDescriptor 包含了HTable的名字和它的所有列族。

HColumnDescriptor 包含了列族的一些信息,像是版本的数量,压缩设置等等。当创建一个表或者是增加一个列的时候,它被用作输入。一旦设定,为列制定的参数只能通过先删除列再重新创建来实现。如果这个列中存储了数据,删除列的同时也会删除数据。

HBaseAdmin提供了管理HBase数据库表元数据的借口,和通用的管理功能。使用它来创建、删除、列出、打开和关闭表。添加和删除列族也是使用它。

抱歉!评论已关闭.