HBase Java programming example

Source: Internet
Author: User

HBase Java programming example
HelloWorld.zip

  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 java. util. concurrent. ExecutorService;
  9. Import java. util. concurrent. Executors;
  10. Import java. util. concurrent. TimeUnit;

  11. Import org. apache. hadoop. conf. Configuration;
  12. Import org. apache. hadoop. hbase. Cell;
  13. Import org. apache. hadoop. hbase. HBaseConfiguration;
  14. Import org. apache. hadoop. hbase. HColumnDescriptor;
  15. Import org. apache. hadoop. hbase. HTableDescriptor;
  16. Import org. apache. hadoop. hbase. MasterNotRunningException;
  17. Import org. apache. hadoop. hbase. TableName;
  18. Import org. apache. hadoop. hbase. ZooKeeperConnectionException;
  19. Import org. apache. hadoop. hbase. client. Delete;
  20. Import org. apache. hadoop. hbase. client. Get;
  21. Import org. apache. hadoop. hbase. client. Admin;
  22. Import org. apache. hadoop. hbase. client. BufferedMutator;
  23. Import org. apache. hadoop. hbase. client. BufferedMutatorParams;
  24. Import org. apache. hadoop. hbase. client. Connection;
  25. Import org. apache. hadoop. hbase. client. ConnectionFactory;
  26. Import org. apache. hadoop. hbase. client. Table;
  27. Import org. apache. hadoop. hbase. client. Put;
  28. Import org. apache. hadoop. hbase. client. Result;
  29. Import org. apache. hadoop. hbase. client. resultworkflow;
  30. Import org. apache. hadoop. hbase. client. Scan;
  31. Import org. apache. hadoop. hbase. util. Bytes;
  32. Import org. apache. hadoop. util. ThreadUtil;

  33. Public class HelloWorld {
  34. Private static Configuration conf = null;
  35. Private static Connection conn = null;
  36. Private static Admin admin = null;
  37. Public static AtomicInteger count = new AtomicInteger ();

  38. /**
  39. * Initialization Configuration
  40. */
  41. Static {
  42. Conf = HBaseConfiguration. create ();
  43. // If no configuration file exists, you must remember the manual announcement.

  44. Conf. set ("hbase. zookeeper. quorum", "10.148.137.143 ");
  45. Conf. set ("hbase. zookeeper. property. clientPort", "2181 ");
  46. }

  47. Static {
  48. Try {
  49. Conn = ConnectionFactory. createConnection ();
  50. Admin = conn. getAdmin ();
  51. } Catch (IOException e ){
  52. E. printStackTrace ();
  53. }
  54. }

  55. Static public class MyThread extends Thread
  56. {
  57. Int _ start;
  58. String _ tablename;
  59. Connection conn;
  60. // BufferedMutator table;
  61. Table table;

  62. Public MyThread (int start, String tablename ){
  63. _ Start = start;
  64. _ Tablename = tablename;
  65. }

  66. Public void run (){
  67. String tablename = _ tablename;
  68. Thread current = Thread. currentThread ();
  69. Long thread_id = current. getId ();
  70. System. out. printf ("thread [% d] run \ n", thread_id );

  71. Try {
  72. Conn = ConnectionFactory. createConnection ();
  73. // BufferedMutatorParams params = new BufferedMutatorParams (TableName. valueOf (tablename ));
  74. // Params. writeBufferSize (1024*4 );
  75. // Table = conn. getBufferedMutator (params );
  76. Table = conn. getTable (TableName. valueOf (tablename ));

  77. For (int j = _ start; j <100; ++ j ){
  78. For (int I = 0; I <10000000; ++ I ){
  79. // Zkb_0_0
  80. String zkb = "zkb _" + String. valueOf (_ start) + "_" + String. valueOf (I );
  81. Put put = new Put (Bytes. toBytes (zkb ));
  82. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field1"), Bytes. toBytes (String. valueOf (I + 0 )));
  83. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field2"), Bytes. toBytes (String. valueOf (I + 1 )));
  84. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field3"), Bytes. toBytes (String. valueOf (I + 2 )));
  85. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field4"), Bytes. toBytes (String. valueOf (I + 3 )));
  86. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field5"), Bytes. toBytes (String. valueOf (I + 4 )));
  87. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field6"), Bytes. toBytes (String. valueOf (I + 5 )));
  88. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field7"), Bytes. toBytes (String. valueOf (I + 6 )));
  89. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field8"), Bytes. toBytes (String. valueOf (I + 7 )));
  90. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field9"), Bytes. toBytes (String. valueOf (I + 8 )));
  91. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field10"), Bytes. toBytes (String. valueOf (I + 9 )));
  92. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field11"), Bytes. toBytes (String. valueOf (I + 10 )));
  93. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field12"), Bytes. toBytes (String. valueOf (I + 11 )));
  94. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field13"), Bytes. toBytes (String. valueOf (I + 12 )));
  95. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field14"), Bytes. toBytes (String. valueOf (I + 13 )));
  96. Put. addColumn (Bytes. toBytes ("grade"), Bytes. toBytes ("field15"), Bytes. toBytes (String. valueOf (I + 14 )));
  97. // Table. mutate (put );
  98. Table. put (put );

  99. Int m = HelloWorld. count. incrementAndGet ();
  100. If (m % 10000 = 0 ){
  101. Date dt = new Date ();
  102. SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss aa ");
  103. String now = sdf. format (dt );
  104. System. out. printf ("[% s] thread [% d] m = % d, j = % d, I = % d \ n", now, thread_id, m, j, I );
  105. }
  106. }
  107. }

  108. System. out. printf ("thread [% d] over \ n", thread_id );
  109. }
  110. Catch (Exception e ){
  111. E. printStackTrace ();
  112. }
  113. }
  114. }

  115. /**
  116. * Create a table
  117. * @ Param tablename
  118. * @ Param cfs
  119. */
  120. Public static void createTable (String tablename, String [] cfs ){
  121. Try {
  122. If (admin. tableExists (TableName. valueOf (tablename ))){
  123. System. out. println ("table already exists! ");
  124. } Else {
  125. HTableDescriptor tableDesc = new HTableDescriptor (TableName. valueOf (tablename ));
  126. For (int I = 0; I <cfs. length; I ++ ){
  127. HColumnDescriptor desc = new HColumnDescriptor (cfs [I]);
  128. Desc. setMaxVersions (3650 );
  129. TableDesc. addFamily (desc );
  130. }

  131. Byte [] [] splitKeys = new byte [] [] {
  132. Bytes. toBytes ("zkb_0_0 "),
  133. Bytes. toBytes ("zkb_10_0 "),
  134. Bytes. toBytes ("zkb_20_0 "),
  135. Bytes. toBytes ("zkb_30_0 "),
  136. Bytes. toBytes ("zkb_40_0 "),
  137. Bytes. toBytes ("zkb_50_0 "),
  138. Bytes. toBytes ("zkb_60_0 "),
  139. Bytes. toBytes ("zkb_70_0 "),
  140. Bytes. toBytes ("zkb_80_0 "),
  141. Bytes. toBytes ("zkb_90_0 "),
  142. Bytes. toBytes ("zkb_100_0 ")
  143. };
  144. Admin. createTable (tableDesc, splitKeys );
  145. Admin. close ();
  146. System. out. println ("create table" + tablename + "OK .");
  147. }
  148. } Catch (MasterNotRunningException e ){
  149. E. printStackTrace ();
  150. } Catch (ZooKeeperConnectionException e ){
  151. E. printStackTrace ();
  152. } Catch (IOException e ){
  153. E. printStackTrace ();
  154. }
  155. }

  156. /**
  157. * Except tables
  158. * @ Param tablename
  159. */
  160. Public static void deleteTable (String tablename ){
  161. Try {
  162. // Connection conn = ConnectionFactory. createConnection ();
  163. // Admin admin = conn. getAdmin ();
  164. Admin. disableTable (TableName. valueOf (tablename ));
  165. Admin. deleteTable (TableName. valueOf (tablename ));
  166. System. out. println ("delete table" + tablename + "OK .");
  167. } Catch (IOException e ){
  168. E. printStackTrace ();
  169. }
  170. }

  171. /**
  172. * Just remove one item
  173. * @ Param tableName
  174. * @ Param rowKey
  175. */
  176. Public static void delRecord (String tableName, String rowKey ){
  177. Try {
  178. Table table = conn. getTable (TableName. valueOf (tableName ));

  179. List <Delete> list = new ArrayList <Delete> ();
  180. Delete del = new Delete (rowKey. getBytes ());
  181. List. add (del );
  182. Table. delete (list );
  183. System. out. println ("del recored" + rowKey + "OK .");
  184. } Catch (IOException e ){
  185. E. printStackTrace ();
  186. }
  187. }

  188. /**
  189. * Obtain a metadata
  190. * @ Param tableName
  191. * @ Param rowKey
  192. */
  193. Public static void getOneRecord (String tableName, String rowKey ){
  194. Try {
  195. Table table = conn. getTable (TableName. valueOf (tableName ));

  196. Get get = new Get (rowKey. getBytes ());
  197. Result rs = table. get (get );
  198. List <Cell> list = rs. listCells ();
  199. For (Cell cell: list ){
  200. System. out. print (new String (cell. getRowArray (), cell. getRowOffset (), cell. getRowLength () + "");
  201. System. out. print (new String (cell. getFamilyArray (), cell. getFamilyOffset (), cell. getFamilyLength () + ":");
  202. System. out. print (new String (cell. getQualifierArray (), cell. getQualifierOffset (), cell. getQualifierLength () + "");
  203. System. out. print (cell. getTimestamp () + "");
  204. System. out. print (new String (cell. getValueArray (), cell. getValueOffset (), cell. getValueLength () + "");
  205. System. out. println ("");
  206. }
  207. } Catch (IOException e ){
  208. E. printStackTrace ();
  209. }
  210. }

  211. /**
  212. * Retrieve all information
  213. * @ Param tableName
  214. */
  215. Public static void getAllRecord (String tableName ){
  216. Try {
  217. // Connection conn = ConnectionFactory. createConnection ();
  218. Table table = conn. getTable (TableName. valueOf (tableName ));

  219. Scan scan = new Scan ();
  220. Resultpartition = table. getpartition (scan );
  221. For (Result rs: resulttasks ){
  222. List <Cell> list = rs. listCells ();
  223. For (Cell cell: list ){
  224. System. out. print (new String (cell. getRowArray (), cell. getRowOffset (), cell. getRowLength () + "");
  225. System. out. print (new String (cell. getFamilyArray (), cell. getFamilyOffset (), cell. getFamilyLength () + ":");
  226. System. out. print (new String (cell. getQualifierArray (), cell. getQualifierOffset (), cell. getQualifierLength () + "");
  227. System. out. print (cell. getTimestamp () + "");
  228. System. out. print (new String (cell. getValueArray (), cell. getValueOffset (), cell. getValueLength () + "");
  229. System. out. println ("");
  230. }
  231. }
  232. } Catch (IOException e ){
  233. E. printStackTrace ();
  234. }
  235. }

  236. /**
  237. * Retrieve the Family ticket
  238. * @ Param tableName
  239. * @ Return
  240. */
  241. Public static ArrayList <String> getAllFamilyName (String tableName ){
  242. ArrayList <String> familyname_list = new ArrayList <String> ();
  243. Try {
  244. // Connection conn = ConnectionFactory. createConnection ();
  245. Table table = conn. getTable (TableName. valueOf (tableName ));

  246. HTableDescriptor htabledescriptor = table. getTableDescriptor ();
  247. HColumnDescriptor [] hdlist = htabledescriptor. getColumnFamilies ();
  248. For (int I = 0; I
  249. HColumnDescriptor hd = hdlist [I];
  250. Familyname_list.add (hd. getNameAsString ());
  251. }
  252. } Catch (IOException e ){
  253. E. printStackTrace ();
  254. }
  255. Return familyname_list;
  256. }

  257. // Java-cp HelloWorld. jar: 'ls lib/*. jar | awk '{printf ("% s:", $0)} ''elementary. HelloWorld 5
  258. Public static void main (String [] args ){
  259. System. out. println ("HelloWorldX ");
  260. If (args. length> 0)
  261. System. out. println (args [0]);

  262. Int start = 0;
  263. If (args. length> 1)
  264. Start = Integer. valueOf (args [1]);
  265. If (start <0)
  266. Start = 0;

  267. Int num_threads = 16;
  268. If (args. length> 2)
  269. Num_threads = Integer. valueOf (args [2]);

  270. Try {
  271. String tablename = "scores ";
  272. String [] familys = {"grade", "course "};
  273. HelloWorld. createTable (tablename, familys );

  274. // ExecutorService thread_pool = Executors. newSingleThreadExecutor ();
  275. ExecutorService thread_pool = Executors. newFixedThreadPool (num_threads );
  276. Thread [] pool = new HelloWorld. MyThread [80];
  277. For (int I = 0; I <pool. length; ++ I ){
  278. Pool [I] = new HelloWorld. MyThread (I, tablename );
  279. Thread_pool.execute (pool [I]);
  280. }

  281. Thread_pool.shutdown ();
  282. System. out. println ("over ");
  283. }
  284. Catch (Exception e ){
  285. E. printStackTrace ();
  286. }
  287. }

  288. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.