HBase Java 編程示例詳解
HelloWorld.zip
下面這份 HelloWorld 示例展示了如何用 Java 操作 HBase,涵蓋了連接建立、建表、刪表、寫入、讀取、掃描等常見操作,並示範了多執行緒併發寫入的寫法。程式碼如下:
- package elementary;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import java.util.concurrent.atomic.AtomicInteger;
- import org.apache.hadoop.conf.Configuration;
- import org.apache.hadoop.hbase.Cell;
- 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.TableName;
- import org.apache.hadoop.hbase.ZooKeeperConnectionException;
- import org.apache.hadoop.hbase.client.Delete;
- import org.apache.hadoop.hbase.client.Get;
- import org.apache.hadoop.hbase.client.Admin;
- import org.apache.hadoop.hbase.client.Connection;
- import org.apache.hadoop.hbase.client.ConnectionFactory;
- import org.apache.hadoop.hbase.client.Table;
- 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 HelloWorld {
- private static Configuration conf = null;
- private static Connection conn = null;
- private static Admin admin = null;
- public static AtomicInteger count = new AtomicInteger();
- // 初始化配置
- static {
- conf = HBaseConfiguration.create();
- // 如果沒有配置文件,一定要記得手動宣告
- conf.set("hbase.zookeeper.quorum", "10.148.137.143");
- conf.set("hbase.zookeeper.property.clientPort", "2181");
- }
- static {
- try {
- conn = ConnectionFactory.createConnection();
- admin = conn.getAdmin();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- // 多執行緒寫入
- static public class MyThread extends Thread {
- int _start;
- String _tablename;
- Connection conn;
- Table table;
- public MyThread(int start, String tablename) {
- _start = start;
- _tablename = tablename;
- }
- public void run() {
- String tablename = _tablename;
- Thread current = Thread.currentThread();
- long thread_id = current.getId();
- System.out.printf("thread[%d] run\n", thread_id);
- try {
- conn = ConnectionFactory.createConnection();
- table = conn.getTable(TableName.valueOf(tablename));
- for (int j = _start; j < 100; ++j) {
- for (int i = 0; i < 10000000; ++i) {
- String zkb = "zkb_" + String.valueOf(_start) + "_" + String.valueOf(i);
- Put put = new Put(Bytes.toBytes(zkb));
- put.addColumn(Bytes.toBytes("grade"), Bytes.toBytes("field1"), Bytes.toBytes(String.valueOf(i + 0)));
- put.addColumn(Bytes.toBytes("grade"), Bytes.toBytes("field2"), Bytes.toBytes(String.valueOf(i + 1)));
- // ...其餘 field3 ~ field15 依此類推
- table.put(put);
- int m = HelloWorld.count.incrementAndGet();
- if (m % 10000 == 0) {
- Date dt = new Date();
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss aa");
- String now = sdf.format(dt);
- System.out.printf("[%s] thread[%d] m=%d, j=%d, i=%d\n", now, thread_id, m, j, i);
- }
- }
- }
- System.out.printf("thread[%d] over\n", thread_id);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- // 建立表格
- public static void createTable(String tablename, String[] cfs) {
- try {
- if (admin.tableExists(TableName.valueOf(tablename))) {
- System.out.println("table already exists!");
- } else {
- HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(tablename));
- for (int i = 0; i < cfs.length; i++) {
- HColumnDescriptor desc = new HColumnDescriptor(cfs[i]);
- desc.setMaxVersions(3650);
- tableDesc.addFamily(desc);
- }
- byte[][] splitKeys = new byte[][] {
- Bytes.toBytes("zkb_0_0"),
- Bytes.toBytes("zkb_10_0"),
- // ... zkb_20_0 ~ zkb_100_0
- };
- admin.createTable(tableDesc, splitKeys);
- admin.close();
- System.out.println("create table " + tablename + " ok.");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- // 刪除表格
- public static void deleteTable(String tablename) {
- try {
- admin.disableTable(TableName.valueOf(tablename));
- admin.deleteTable(TableName.valueOf(tablename));
- System.out.println("delete table " + tablename + " ok.");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- // 刪除一筆資料
- public static void delRecord(String tableName, String rowKey) {
- try {
- Table table = conn.getTable(TableName.valueOf(tableName));
- List<Delete> list = new ArrayList<Delete>();
- Delete del = new Delete(rowKey.getBytes());
- list.add(del);
- table.delete(list);
- System.out.println("del recored " + rowKey + " ok.");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- // 取得一筆資料
- public static void getOneRecord(String tableName, String rowKey) {
- try {
- Table table = conn.getTable(TableName.valueOf(tableName));
- Get get = new Get(rowKey.getBytes());
- Result rs = table.get(get);
- List<Cell> list = rs.listCells();
- for (Cell cell : list) {
- System.out.print(new String(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()) + " ");
- System.out.print(new String(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength()) + ":");
- System.out.print(new String(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()) + " ");
- System.out.print(cell.getTimestamp() + " ");
- System.out.print(new String(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()) + " ");
- System.out.println("");
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- // 取得所有資料
- public static void getAllRecord(String tableName) {
- try {
- Table table = conn.getTable(TableName.valueOf(tableName));
- Scan scan = new Scan();
- ResultScanner resultscanner = table.getScanner(scan);
- for (Result rs : resultscanner) {
- List<Cell> list = rs.listCells();
- for (Cell cell : list) {
- System.out.print(new String(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()) + " ");
- System.out.println("");
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- // 取得 Family 清單
- public static ArrayList<String> getAllFamilyName(String tableName) {
- ArrayList<String> familyname_list = new ArrayList<String>();
- try {
- Table table = conn.getTable(TableName.valueOf(tableName));
- HTableDescriptor htabledescriptor = table.getTableDescriptor();
- HColumnDescriptor[] hdlist = htabledescriptor.getColumnFamilies();
- for (int i = 0; i < hdlist.length; i++) {
- HColumnDescriptor hd = hdlist[i];
- familyname_list.add(hd.getNameAsString());
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return familyname_list;
- }
- public static void main(String[] args) {
- int start = 0;
- if (args.length > 1)
- start = Integer.valueOf(args[1]);
- int num_threads = 16;
- if (args.length > 2)
- num_threads = Integer.valueOf(args[2]);
- try {
- String tablename = "scores";
- String[] familys = { "grade", "course" };
- HelloWorld.createTable(tablename, familys);
- ExecutorService thread_pool = Executors.newFixedThreadPool(num_threads);
- Thread[] pool = new HelloWorld.MyThread[80];
- for (int i = 0; i < pool.length; ++i) {
- pool[i] = new HelloWorld.MyThread(i, tablename);
- thread_pool.execute(pool[i]);
- }
- thread_pool.shutdown();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
這份示例把 HBase 客戶端最常用的 API 都串了起來:透過 ConnectionFactory 建立連接、Admin 管理表結構、Put 寫入、Get 單筆讀取、Scan 全表掃描,並用固定大小的執行緒池做併發寫入壓測。程式的編譯運行命令可寫作:java -cp HelloWorld.jar:`ls lib/*.jar|awk '{printf("%s:", $0)}'` elementary.HelloWorld 5。