關於HBase的前後因果先不討論,現在寫一個Hbase實例,怎麼樣去創建一個Hbase的列簇.
public class HbaseTable {
//定義一個hbase連接Configuration conf = null;
//構造方法初始化,連接到hbase數據庫
HbaseIf() {
//創建Hbase數據庫的連接,默認本地
conf=HBaseConfiguration.create();
}
//創建一個Table
public void create_table(String name, String col, int version)
throws Exception {
//創建一個對象,連接到Hbase
HBaseAdmin admin = new HBaseAdmin(conf);
//判斷一個Tbale是否存在,若存在,則刪除該Table
if (admin.tableExists(name)) {
admin.disableTable(name);
admin.deleteTable(name);
}
//初始化Tbale,傳入Table名稱
HTableDescriptor htd = new HTableDescriptor(name);
//初始化列,傳入列名稱
HColumnDescriptor hcd = new HColumnDescriptor(col);
//設置Hbase最大版本號
hcd.setMaxVersions(1);
//網一個Table中插入一個列簇
htd.addFamily(hcd);
//創建一個Tbale
admin.createTable(htd);
}
/*
* tab_global param:userid
*
* tab_user2id info:id
*
* tab_id2user info:username, info:password
*/
public void createTables() throws Exception {
//創建一個名爲tab_global的Table,列爲param的列
create_table("tab_global","param",1);
//創建一個名爲row_userid的RowKey,Hbase都是村二進制的數據所以要轉化的Byte
Put put=new Put(Bytes.toBytes("row_userid"));
int i=1;
//在列簇中創建一條數據,列簇名是param:userid
put.add(Bytes.toBytes("param"), Bytes.toBytes("userid"), Bytes.toBytes(i));
//往Table裏插入數據
HTable ht=new HTable(conf,"tab_global");
ht.put(put);
//創建一個名爲tab_user2id的Table,列爲info的列
create_table("tab_user2id","info",1);
create_table("tab_id2user","info",1);
}
public static void main(String[] args) throws Exception {
HbaseTable hbase=new HbaseTable();
hbase.createTables();
}
} 運行該對象數據即可插入。
驗證:在hbase shell中輸入 list 會出現三個表
tab_global
tab_id2user
tab_user2id
輸入:scan 'tab_global' 會出現插入的數據
hbase(main):002:0> scan 'tab_global'
ROW COLUMN+CELL
row_userid column=param:userid, timestamp=1377096845757, value=\x00\x00\x00\x01
如圖: