Java操作HBase
package Hbase;
import org.apache.Hadoop.conf.Configuration;
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.TableDescriptors;
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;
public class HBaseAPP {
private static final String TABLE_NAME = "table1";
private static final String FAMILY_NAME = "family1";
private static final String ROW_KEYS = "rowKey1";
public static void main(String[] args) throws Exception {
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.rootdir", "hdfs://hadoop1:9000/hbase");
// 使用eclipse時必須添加這個,否則無法定位
conf.set("hbase.zookeeper.quorum", "hadoop1");
// HBaseAdmin用來創建表 刪除表使用 alt+shift+l 抽取變量
HBaseAdmin hBaseAdmin = new HBaseAdmin(conf);
//創建表
//createTable(hBaseAdmin);
//刪除表
//deleteTable(hBaseAdmin);
// HTable 插入 查詢 使用
HTable hTable = new HTable(conf, TABLE_NAME);
//插入記錄
//putRecord(hTable);
//查詢記錄
//getRecord(hTable);
//掃面
//scanRecord(hTable);
}
private static void scanRecord(HTable hTable) throws IOException {
Scan scan = new Scan();
ResultScanner scanner = hTable.getScanner(scan);
for (Result result : scanner) {
byte[] value = result.getValue(FAMILY_NAME.getBytes(), "age".getBytes());
System.out.println(result+"\t"+new String(value));
}
}
private static void getRecord(HTable hTable) throws IOException {
Get get = new Get(ROW_KEYS.getBytes());
Result result = hTable.get(get);
byte[] value = result.getValue(FAMILY_NAME.getBytes(), "age".getBytes());
System.out.println(new String(value));
}
private static void putRecord(HTable hTable) throws IOException {
Put put = new Put(ROW_KEYS.getBytes());
put.add(FAMILY_NAME.getBytes(), "age".getBytes(), "28".getBytes());
hTable.put(put);
hTable.close();
}
private static void deleteTable(final HBaseAdmin hBaseAdmin)
throws IOException {
hBaseAdmin.disableTable(TABLE_NAME);
hBaseAdmin.deleteTable(TABLE_NAME);
}
private static void createTable(HBaseAdmin hBaseAdmin) throws IOException {
if (!(hBaseAdmin.tableExists(TABLE_NAME))) {
HTableDescriptor hTableDescriptor = new HTableDescriptor(TABLE_NAME);
HColumnDescriptor family = new HColumnDescriptor(FAMILY_NAME);
hTableDescriptor.addFamily(family);
hBaseAdmin.createTable(hTableDescriptor);
}
}
}
HBase 的詳細介紹:請點這裡
HBase 的下載地址:請點這裡