使用java操作HBase

前提:

HBase版本为 hbase0.94.18.tar.gz

使用HBase的Java api,对HBase进行操作。

 

1、连接hbase

//设置配置信息
public Configuration getConfig() {
	Configuration conf = HBaseConfiguration.create();
	conf.set("hbase.master", "192.168.206.21:60000");
	conf.set("hbase.zookeeper.quorum", "192.168.206.22,192.168.206.23,192.168.206.24");
	conf.set("hbase.zookeeper.property.clientport", "2181");
	return conf;
}

2、在hbase中创建表

// 创建表
public boolean createTable(Configuration conf, String tableName) {

	boolean result = false;
	HBaseAdmin hBaseAdmin = null;
	try {
		hBaseAdmin = new HBaseAdmin(conf);
		if (hBaseAdmin.tableExists(tableName)) {
			hBaseAdmin.disableTable(tableName);
			hBaseAdmin.deleteTable(tableName);
		}
		HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
		hTableDescriptor.addFamily(new HColumnDescriptor("columnFamily1"));
		hBaseAdmin.createTable(hTableDescriptor);
		result = true;
	} catch (MasterNotRunningException e) {
		e.printStackTrace();
		result = false;
	} catch (ZooKeeperConnectionException e) {
		e.printStackTrace();
		result = false;
	} catch (IOException e) {
		e.printStackTrace();
		result = false;
	} finally {
		try {
			hBaseAdmin.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return result;
}

3、往HBase插入记录

// 插入一条记录
public boolean putRowIntoTable(Configuration conf,String tableName){
	boolean result = false;
	HTable hTable = null;
	try {
		hTable = new HTable(conf, tableName);
		Put put = new Put("rowkey001".getBytes());
		put.add("columnFamily1".getBytes(),"column1".getBytes(),"value1".getBytes());
		put.add("columnFamily1".getBytes(),"column2".getBytes(),"value2".getBytes());
		hTable.put(put);
		result = true;
	} catch (IOException e) {
		e.printStackTrace();
		result = false;
	}finally {
		try {
			hTable.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return result;
}

4、删除记录

// 删除一条记录
public boolean deleteRow(Configuration conf,String hTableName,String rowKey){
	boolean result = false;
	HTable hTable  = null;
	try {
		hTable = new HTable(conf,hTableName);
		hTable.delete(new Delete(rowKey.getBytes()));
		result = true;
	} catch (IOException e) {
		e.printStackTrace();
		result = false;
	}finally {
		try {
			hTable.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return result;
}

5、删除表

//删除表
public boolean dropTable(Configuration conf, String tableName){
	boolean result = false;
	HBaseAdmin hBaseAdmin = null;
	try {
		hBaseAdmin = new HBaseAdmin(conf);
		if(hBaseAdmin.tableExists(tableName)){
			hBaseAdmin.disableTable(tableName);
			hBaseAdmin.deleteTable(tableName);
		}else{
			System.err.println(tableName + " is not exist!");
		}
		result = true;
	} catch (IOException e) {
		e.printStackTrace();
		result = false;
	}finally {
		try {
			hBaseAdmin.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return result;
}

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注