Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

HBase Java 編程實戰入門示例

編輯:關於 Android 開發

HBase Java 編程示例詳解

HelloWorld.zip

下面這份 HelloWorld 示例展示了如何用 Java 操作 HBase,涵蓋了連接建立、建表、刪表、寫入、讀取、掃描等常見操作,並示範了多執行緒併發寫入的寫法。程式碼如下:

  1. package elementary;
  2. import java.io.IOException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.ArrayList;
  5. import java.util.Date;
  6. import java.util.List;
  7. import java.util.concurrent.atomic.AtomicInteger;
  8. import org.apache.hadoop.conf.Configuration;
  9. import org.apache.hadoop.hbase.Cell;
  10. import org.apache.hadoop.hbase.HBaseConfiguration;
  11. import org.apache.hadoop.hbase.HColumnDescriptor;
  12. import org.apache.hadoop.hbase.HTableDescriptor;
  13. import org.apache.hadoop.hbase.MasterNotRunningException;
  14. import org.apache.hadoop.hbase.TableName;
  15. import org.apache.hadoop.hbase.ZooKeeperConnectionException;
  16. import org.apache.hadoop.hbase.client.Delete;
  17. import org.apache.hadoop.hbase.client.Get;
  18. import org.apache.hadoop.hbase.client.Admin;
  19. import org.apache.hadoop.hbase.client.Connection;
  20. import org.apache.hadoop.hbase.client.ConnectionFactory;
  21. import org.apache.hadoop.hbase.client.Table;
  22. import org.apache.hadoop.hbase.client.Put;
  23. import org.apache.hadoop.hbase.client.Result;
  24. import org.apache.hadoop.hbase.client.ResultScanner;
  25. import org.apache.hadoop.hbase.client.Scan;
  26. import org.apache.hadoop.hbase.util.Bytes;
  27. public class HelloWorld {
  28. private static Configuration conf = null;
  29. private static Connection conn = null;
  30. private static Admin admin = null;
  31. public static AtomicInteger count = new AtomicInteger();
  32. // 初始化配置
  33. static {
  34. conf = HBaseConfiguration.create();
  35. // 如果沒有配置文件,一定要記得手動宣告
  36. conf.set("hbase.zookeeper.quorum", "10.148.137.143");
  37. conf.set("hbase.zookeeper.property.clientPort", "2181");
  38. }
  39. static {
  40. try {
  41. conn = ConnectionFactory.createConnection();
  42. admin = conn.getAdmin();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. // 多執行緒寫入
  48. static public class MyThread extends Thread {
  49. int _start;
  50. String _tablename;
  51. Connection conn;
  52. Table table;
  53. public MyThread(int start, String tablename) {
  54. _start = start;
  55. _tablename = tablename;
  56. }
  57. public void run() {
  58. String tablename = _tablename;
  59. Thread current = Thread.currentThread();
  60. long thread_id = current.getId();
  61. System.out.printf("thread[%d] run\n", thread_id);
  62. try {
  63. conn = ConnectionFactory.createConnection();
  64. table = conn.getTable(TableName.valueOf(tablename));
  65. for (int j = _start; j < 100; ++j) {
  66. for (int i = 0; i < 10000000; ++i) {
  67. String zkb = "zkb_" + String.valueOf(_start) + "_" + String.valueOf(i);
  68. Put put = new Put(Bytes.toBytes(zkb));
  69. put.addColumn(Bytes.toBytes("grade"), Bytes.toBytes("field1"), Bytes.toBytes(String.valueOf(i + 0)));
  70. put.addColumn(Bytes.toBytes("grade"), Bytes.toBytes("field2"), Bytes.toBytes(String.valueOf(i + 1)));
  71. // ...其餘 field3 ~ field15 依此類推
  72. table.put(put);
  73. int m = HelloWorld.count.incrementAndGet();
  74. if (m % 10000 == 0) {
  75. Date dt = new Date();
  76. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss aa");
  77. String now = sdf.format(dt);
  78. System.out.printf("[%s] thread[%d] m=%d, j=%d, i=%d\n", now, thread_id, m, j, i);
  79. }
  80. }
  81. }
  82. System.out.printf("thread[%d] over\n", thread_id);
  83. } catch (Exception e) {
  84. e.printStackTrace();
  85. }
  86. }
  87. }
  88. // 建立表格
  89. public static void createTable(String tablename, String[] cfs) {
  90. try {
  91. if (admin.tableExists(TableName.valueOf(tablename))) {
  92. System.out.println("table already exists!");
  93. } else {
  94. HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(tablename));
  95. for (int i = 0; i < cfs.length; i++) {
  96. HColumnDescriptor desc = new HColumnDescriptor(cfs[i]);
  97. desc.setMaxVersions(3650);
  98. tableDesc.addFamily(desc);
  99. }
  100. byte[][] splitKeys = new byte[][] {
  101. Bytes.toBytes("zkb_0_0"),
  102. Bytes.toBytes("zkb_10_0"),
  103. // ... zkb_20_0 ~ zkb_100_0
  104. };
  105. admin.createTable(tableDesc, splitKeys);
  106. admin.close();
  107. System.out.println("create table " + tablename + " ok.");
  108. }
  109. } catch (Exception e) {
  110. e.printStackTrace();
  111. }
  112. }
  113. // 刪除表格
  114. public static void deleteTable(String tablename) {
  115. try {
  116. admin.disableTable(TableName.valueOf(tablename));
  117. admin.deleteTable(TableName.valueOf(tablename));
  118. System.out.println("delete table " + tablename + " ok.");
  119. } catch (IOException e) {
  120. e.printStackTrace();
  121. }
  122. }
  123. // 刪除一筆資料
  124. public static void delRecord(String tableName, String rowKey) {
  125. try {
  126. Table table = conn.getTable(TableName.valueOf(tableName));
  127. List<Delete> list = new ArrayList<Delete>();
  128. Delete del = new Delete(rowKey.getBytes());
  129. list.add(del);
  130. table.delete(list);
  131. System.out.println("del recored " + rowKey + " ok.");
  132. } catch (IOException e) {
  133. e.printStackTrace();
  134. }
  135. }
  136. // 取得一筆資料
  137. public static void getOneRecord(String tableName, String rowKey) {
  138. try {
  139. Table table = conn.getTable(TableName.valueOf(tableName));
  140. Get get = new Get(rowKey.getBytes());
  141. Result rs = table.get(get);
  142. List<Cell> list = rs.listCells();
  143. for (Cell cell : list) {
  144. System.out.print(new String(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()) + " ");
  145. System.out.print(new String(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength()) + ":");
  146. System.out.print(new String(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()) + " ");
  147. System.out.print(cell.getTimestamp() + " ");
  148. System.out.print(new String(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()) + " ");
  149. System.out.println("");
  150. }
  151. } catch (IOException e) {
  152. e.printStackTrace();
  153. }
  154. }
  155. // 取得所有資料
  156. public static void getAllRecord(String tableName) {
  157. try {
  158. Table table = conn.getTable(TableName.valueOf(tableName));
  159. Scan scan = new Scan();
  160. ResultScanner resultscanner = table.getScanner(scan);
  161. for (Result rs : resultscanner) {
  162. List<Cell> list = rs.listCells();
  163. for (Cell cell : list) {
  164. System.out.print(new String(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()) + " ");
  165. System.out.println("");
  166. }
  167. }
  168. } catch (IOException e) {
  169. e.printStackTrace();
  170. }
  171. }
  172. // 取得 Family 清單
  173. public static ArrayList<String> getAllFamilyName(String tableName) {
  174. ArrayList<String> familyname_list = new ArrayList<String>();
  175. try {
  176. Table table = conn.getTable(TableName.valueOf(tableName));
  177. HTableDescriptor htabledescriptor = table.getTableDescriptor();
  178. HColumnDescriptor[] hdlist = htabledescriptor.getColumnFamilies();
  179. for (int i = 0; i < hdlist.length; i++) {
  180. HColumnDescriptor hd = hdlist[i];
  181. familyname_list.add(hd.getNameAsString());
  182. }
  183. } catch (IOException e) {
  184. e.printStackTrace();
  185. }
  186. return familyname_list;
  187. }
  188. public static void main(String[] args) {
  189. int start = 0;
  190. if (args.length > 1)
  191. start = Integer.valueOf(args[1]);
  192. int num_threads = 16;
  193. if (args.length > 2)
  194. num_threads = Integer.valueOf(args[2]);
  195. try {
  196. String tablename = "scores";
  197. String[] familys = { "grade", "course" };
  198. HelloWorld.createTable(tablename, familys);
  199. ExecutorService thread_pool = Executors.newFixedThreadPool(num_threads);
  200. Thread[] pool = new HelloWorld.MyThread[80];
  201. for (int i = 0; i < pool.length; ++i) {
  202. pool[i] = new HelloWorld.MyThread(i, tablename);
  203. thread_pool.execute(pool[i]);
  204. }
  205. thread_pool.shutdown();
  206. } catch (Exception e) {
  207. e.printStackTrace();
  208. }
  209. }
  210. }

這份示例把 HBase 客戶端最常用的 API 都串了起來:透過 ConnectionFactory 建立連接、Admin 管理表結構、Put 寫入、Get 單筆讀取、Scan 全表掃描,並用固定大小的執行緒池做併發寫入壓測。程式的編譯運行命令可寫作:java -cp HelloWorld.jar:`ls lib/*.jar|awk '{printf("%s:", $0)}'` elementary.HelloWorld 5。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved