JAVA操作Hbase

實際開發(fā)中可以利用javaAPI去操作控制Hbase

【準備】
1:開啟集群,一次開啟(zookeeper,hdfs,hbase)
2:創(chuàng)建項目允蚣,導入jar
3:代碼實現

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.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.HTablePool;
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;
import org.junit.Before;
import org.junit.Test;

public class HbaseDemo {
    private Configuration conf = null;
    
    @Before
    public void init(){
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "hadoop2004:2181,hadoop2005:2181,hadoop2006:2181");
    }
    
    @Test
    public void testPut() throws Exception{
        HTable table = new HTable(conf, "tab_dog");
        Put put = new Put(Bytes.toBytes("rk0001"));
        put.add(Bytes.toBytes("info"),Bytes.toBytes("name"),Bytes.toBytes("旺財"));
        put.add(Bytes.toBytes("info"),Bytes.toBytes("age"),Bytes.toBytes("3"));
        put.add(Bytes.toBytes("info"),Bytes.toBytes("sex"),Bytes.toBytes("boy"));
        table.put(put);
        table.close();
    }

    @Test
    public void testPutAll() throws Exception{
        HTable table = new HTable(conf, "tab_dog");
        List<Put> puts = new ArrayList<Put>(10000);
        for(int i=0 ; i<1000000; i++){
            Put put = new Put(Bytes.toBytes("rk"+i));
            put.add(Bytes.toBytes("info"), Bytes.toBytes("sal"), Bytes.toBytes(""+i));
            puts.add(put);
            //這里防止數據量過大,內存溢出呆贿,所以10000條就插入一次嚷兔,分批插入
            if(i % 10000 == 0){
                table.put(puts);
                puts = new ArrayList<Put>(10000);
            }
        }
        table.put(puts);
        table.close();
    }
    
    @Test
    public void testGet() throws Exception{
        //HTablePool pool = new HTablePool(conf, 10);
        //HTable table = (HTable) pool.getTable("user");
        HTable table = new HTable(conf, "tab_dog");
        Get get = new Get(Bytes.toBytes("rk0001"));
        //get.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"));
        get.setMaxVersions(5);
        Result result = table.get(get);
        //result.getValue(family, qualifier)
        
        for(KeyValue kv: result.list()){
            String family = new String(kv.getFamily());
            String qualifier = new String(kv.getQualifier());
            String value = new String(kv.getValue());
            System.out.println(family + " " + qualifier + " : "+ value);            
        }
        table.close();
    }
    
    @Test
    public void testScan() throws Exception{
        HTablePool pool = new HTablePool(conf,1000);
        HTableInterface table = pool.getTable("user");
        Scan scan = new Scan(Bytes.toBytes("rk0001"),Bytes.toBytes("rk0002"));
        scan.addFamily(Bytes.toBytes("info"));
        ResultScanner scanner = table.getScanner(scan);
        for(Result r : scanner){
            byte[] name = r.getValue(Bytes.toBytes("info"), Bytes.toBytes("name"));
            byte[] age = r.getValue(Bytes.toBytes("info"), Bytes.toBytes("age"));
            byte[] sex = r.getValue(Bytes.toBytes("info"), Bytes.toBytes("sex"));
            System.out.println(new String(name) + " : " + new String(age) + " : " + new String(sex));
        }
        pool.close();
    }
    
    @Test
    public void testDel() throws Exception{
        HTable table = new HTable(conf,"tab_dog");
        Delete del = new Delete(Bytes.toBytes("rk0001"));
        del.deleteColumn(Bytes.toBytes("info"), Bytes.toBytes("name"));
        table.delete(del);
        table.close();
    }
    
    @Test
    public void testDrop() throws Exception{
        HBaseAdmin admin = new HBaseAdmin(conf);
        admin.disableTable("tab_dog");
        admin.deleteTable("tab_dog");
        admin.close();
    }

    @Test
    public void testCreate() throws Exception {     
        //設置操作用戶(建表要有用戶,誰建的)
        HBaseAdmin admin = new HBaseAdmin(conf);        
        //創(chuàng)建表信息(表名)
        HTableDescriptor desc = new HTableDescriptor(TableName.valueOf("tab_dog"));
        //創(chuàng)建列族
        HColumnDescriptor cd = new HColumnDescriptor("info");
        cd.setMaxVersions(10);
        //添加列族
        desc.addFamily(cd); 
        //創(chuàng)建表
        admin.createTable(desc);
        admin.close();
    }
}
2016-12-23_175418.png
/*
 * 創(chuàng)建一個students表,并進行相關操作
 */
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
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.KeyValue;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
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 HBaseJavaAPI {
    // 聲明靜態(tài)配置
    private static Configuration conf = null;
 
    static {
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "192.168.6.91");
        conf.set("hbase.zookeeper.property.clientPort", "2181");
    }
 
    //判斷表是否存在
    private static boolean isExist(String tableName) throws IOException {
        HBaseAdmin hAdmin = new HBaseAdmin(conf);
        return hAdmin.tableExists(tableName);
    }
 
    // 創(chuàng)建數據庫表
    public static void createTable(String tableName, String[] columnFamilys)
            throws Exception {
        // 新建一個數據庫管理員
        HBaseAdmin hAdmin = new HBaseAdmin(conf);
        if (hAdmin.tableExists(tableName)) {
            System.out.println("表 "+tableName+" 已存在做入!");
            System.exit(0);
        } else {
            // 新建一個students表的描述
            HTableDescriptor tableDesc = new HTableDescriptor(tableName);
            // 在描述里添加列族
            for (String columnFamily : columnFamilys) {
                tableDesc.addFamily(new HColumnDescriptor(columnFamily));
            }
            // 根據配置好的描述建表
            hAdmin.createTable(tableDesc);
            System.out.println("創(chuàng)建表 "+tableName+" 成功!");
        }
    }
 
    // 刪除數據庫表
    public static void deleteTable(String tableName) throws Exception {
        // 新建一個數據庫管理員
        HBaseAdmin hAdmin = new HBaseAdmin(conf);
        if (hAdmin.tableExists(tableName)) {
            // 關閉一個表
            hAdmin.disableTable(tableName);
            hAdmin.deleteTable(tableName);
            System.out.println("刪除表 "+tableName+" 成功冒晰!");
        } else {
            System.out.println("刪除的表 "+tableName+" 不存在!");
            System.exit(0);
        }
    }
 
    // 添加一條數據
    public static void addRow(String tableName, String row,
            String columnFamily, String column, String value) throws Exception {
        HTable table = new HTable(conf, tableName);
        Put put = new Put(Bytes.toBytes(row));// 指定行
        // 參數分別:列族竟块、列壶运、值
        put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column),
                Bytes.toBytes(value));
        table.put(put);
    }
 
    // 刪除一條(行)數據
    public static void delRow(String tableName, String row) throws Exception {
        HTable table = new HTable(conf, tableName);
        Delete del = new Delete(Bytes.toBytes(row));
        table.delete(del);
    }
 
    // 刪除多條數據
    public static void delMultiRows(String tableName, String[] rows)
            throws Exception {
        HTable table = new HTable(conf, tableName);
        List<Delete> delList = new ArrayList<Delete>();
        for (String row : rows) {
            Delete del = new Delete(Bytes.toBytes(row));
            delList.add(del);
        }
        table.delete(delList);
    }
 
    // 獲取一條數據
    public static void getRow(String tableName, String row) throws Exception {
        HTable table = new HTable(conf, tableName);
        Get get = new Get(Bytes.toBytes(row));
        Result result = table.get(get);
        // 輸出結果,raw方法返回所有keyvalue數組
        for (KeyValue rowKV : result.raw()) {
            System.out.print("行名:" + new String(rowKV.getRow()) + " ");
            System.out.print("時間戳:" + rowKV.getTimestamp() + " ");
            System.out.print("列族名:" + new String(rowKV.getFamily()) + " ");
            System.out.print("列名:" + new String(rowKV.getQualifier()) + " ");
            System.out.println("值:" + new String(rowKV.getValue()));
        }
    }
 
    // 獲取所有數據
    public static void getAllRows(String tableName) throws Exception {
        HTable table = new HTable(conf, tableName);
        Scan scan = new Scan();
        ResultScanner results = table.getScanner(scan);
        // 輸出結果
        for (Result result : results) {
            for (KeyValue rowKV : result.raw()) {
                System.out.print("行名:" + new String(rowKV.getRow()) + " ");
                System.out.print("時間戳:" + rowKV.getTimestamp() + " ");
                System.out.print("列族名:" + new String(rowKV.getFamily()) + " ");
                System.out
                        .print("列名:" + new String(rowKV.getQualifier()) + " ");
                System.out.println("值:" + new String(rowKV.getValue()));
            }
        }
    }
 
    // 主函數
    public static void main(String[] args) {
        try {
            String tableName = "student";
            // 第一步:創(chuàng)建數據庫表:“student”
            String[] columnFamilys = { "info", "course" };
            HBaseJavaAPI.createTable(tableName, columnFamilys);
            // 第二步:向數據表的添加數據
            // 添加第一行數據
            if (isExist(tableName)) {
                HBaseJavaAPI.addRow(tableName, "zpc", "info", "age", "20");
                HBaseJavaAPI.addRow(tableName, "zpc", "info", "sex", "boy");
                HBaseJavaAPI.addRow(tableName, "zpc", "course", "china", "97");
                HBaseJavaAPI.addRow(tableName, "zpc", "course", "math", "128");
                HBaseJavaAPI.addRow(tableName, "zpc", "course", "english", "85");
                // 添加第二行數據
                HBaseJavaAPI.addRow(tableName, "henjun", "info", "age", "19");
                HBaseJavaAPI.addRow(tableName, "<span style="font-family: Arial, Helvetica, sans-serif;">henjun</span>", "info", "sex", "boy");
                HBaseJavaAPI.addRow(tableName, "henjun", "course", "china","90");
                HBaseJavaAPI.addRow(tableName, "henjun", "course", "math","120");
                HBaseJavaAPI.addRow(tableName, "henjun", "course", "english","90");
                // 添加第三行數據
                HBaseJavaAPI.addRow(tableName, "niaopeng", "info", "age", "18");
                HBaseJavaAPI.addRow(tableName, "<span style="font-family: Arial, Helvetica, sans-serif;">niaopeng</span>", "info", "sex","girl");
                HBaseJavaAPI.addRow(tableName, "niaopeng", "course", "china","100");
                HBaseJavaAPI.addRow(tableName, "niaopeng", "course", "math","100");
                HBaseJavaAPI.addRow(tableName, "niaopeng", "course", "english","99");
                // 第三步:獲取一條數據
                System.out.println("**************獲取一條(zpc)數據*************");
                HBaseJavaAPI.getRow(tableName, "zpc");
                // 第四步:獲取所有數據
                System.out.println("**************獲取所有數據***************");
                HBaseJavaAPI.getAllRows(tableName);
 
                // 第五步:刪除一條數據
                System.out.println("************刪除一條(zpc)數據************");
                HBaseJavaAPI.delRow(tableName, "zpc");
                HBaseJavaAPI.getAllRows(tableName);
                // 第六步:刪除多條數據
                System.out.println("**************刪除多條數據***************");
                String rows[] = new String[] { "qingqing","xiaoxue" };
                HBaseJavaAPI.delMultiRows(tableName, rows);
                HBaseJavaAPI.getAllRows(tableName);
                // 第七步:刪除數據庫
                System.out.println("***************刪除數據庫表**************");
                HBaseJavaAPI.deleteTable(tableName);
                System.out.println("表"+tableName+"存在嗎?"+isExist(tableName));
            } else {
                System.out.println(tableName + "此數據庫表不存在浪秘!");
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末蒋情,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子耸携,更是在濱河造成了極大的恐慌棵癣,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件夺衍,死亡現場離奇詭異狈谊,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進店門河劝,熙熙樓的掌柜王于貴愁眉苦臉地迎上來渊抄,“玉大人,你說我怎么就攤上這事丧裁。” “怎么了含衔?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵煎娇,是天一觀的道長。 經常有香客問我贪染,道長缓呛,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任杭隙,我火速辦了婚禮哟绊,結果婚禮上,老公的妹妹穿的比我還像新娘痰憎。我一直安慰自己票髓,他們只是感情好,可當我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布铣耘。 她就那樣靜靜地躺著洽沟,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蜗细。 梳的紋絲不亂的頭發(fā)上裆操,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天,我揣著相機與錄音炉媒,去河邊找鬼踪区。 笑死,一個胖子當著我的面吹牛吊骤,可吹牛的內容都是我干的缎岗。 我是一名探鬼主播,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼白粉,長吁一口氣:“原來是場噩夢啊……” “哼博个!你這毒婦竟也來了?” 一聲冷哼從身側響起茅茂,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤旺罢,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后奕扣,有當地人在樹林里發(fā)現了一具尸體薪鹦,經...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了池磁。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片奔害。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖地熄,靈堂內的尸體忽然破棺而出华临,到底是詐尸還是另有隱情,我是刑警寧澤端考,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布雅潭,位于F島的核電站,受9級特大地震影響却特,放射性物質發(fā)生泄漏扶供。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一裂明、第九天 我趴在偏房一處隱蔽的房頂上張望椿浓。 院中可真熱鬧,春花似錦闽晦、人聲如沸扳碍。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽左腔。三九已至,卻和暖如春捅儒,著一層夾襖步出監(jiān)牢的瞬間液样,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工巧还, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留鞭莽,地道東北人。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓麸祷,卻偏偏與公主長得像澎怒,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子阶牍,可洞房花燭夜當晚...
    茶點故事閱讀 45,515評論 2 359

推薦閱讀更多精彩內容