{{{ #!html
HBase 進階課程
程式範例練習
}}} [wiki:NCHCCloudCourse110721#第二天 回課程大綱 << ] 第一關 [wiki:NCHCCloudCourse100929_4_HBEX2 > 下一關 ] = 注意 = * 請將以下給個 hbase 重要的檔複製到 hadoop lib 目錄下,並且重新啟動 hbase 與 hadoop {{{ $ cd /opt/hbase $ cp hbase-*.jar lib/zookeeper-3.2.2.jar contrib/transactional/hbase-0.20.6-transactional.jar /opt/hadoop/lib/ $ /opt/hbase/bin/stop-hbase.sh $ /opt/hadoop/bin/stop-all.sh $ /opt/hadoop/bin/start-all.sh $ /opt/hbase/bin/start-hbase.sh }}} * 若編譯以下範例的環境為console 端,請設定完整的classpath,詳細方法請看教材投影片 * 若開發是透過 eclipse ,請將 hbase-core.jar , zookeeper*.jar , hbase-*-transactional.jar 匯入到 project library 中,詳細方法請看教材投影片 * 注意: 若此程式執行於 eclipse ,則方便起見,請將程式的 eclipse only 的後兩行的註解取消,如: {{{ #!java // eclipse only String[] args = {"ex1Table","Detail"}; argv = args; }}} = 範例一:新增Table = {{{ bin/hadoop jar TCRCExample.jar CreateTable ex1Table Detail }}} = !CreateTable.java = {{{ #!java package org.nchc.hbase; 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.client.HBaseAdmin; import org.apache.hadoop.util.GenericOptionsParser; public class CreateTable { public static void createHBaseTable(String tablename, String family) throws IOException { // HTableDescriptor 用來描述table的屬性 HTableDescriptor htd = new HTableDescriptor(tablename); // HTableDescriptor 透過 add() 方法來加入Column family htd.addFamily(new HColumnDescriptor(family)); // HBaseConfiguration 能接收 hbase-site.xml 的設定值 HBaseConfiguration config = new HBaseConfiguration(); // 檔案的操作則使用 HBaseAdmin HBaseAdmin admin = new HBaseAdmin(config); // 檢查 if (admin.tableExists(tablename)) { System.out.println("Table: " + tablename + "Existed."); } else { // 建立 admin.createTable(htd); // System.out.println( tablename + " created."); } } static public void main(String argv[]) throws IOException { // eclipse only // String[] args = {"ex1Table","Detail"}; // argv = args; String[] otherArgs = new GenericOptionsParser(new Configuration(), argv) .getRemainingArgs(); if (otherArgs.length < 2) { System.out.println("CreateTable "); return; } String tablename = otherArgs[0]; String family = otherArgs[1]; System.out.println("1. create table :" + tablename); createHBaseTable(tablename, family); } } }}} * 執行結果 {{{ 1. create table :ex1Table ex1Table created. }}}