Java代码中Hbase的使用

hbase简介

HBase是一个分布式的、面向列的开源数据库,该技术来源于 Fay Chang 所撰写的Google论文“Bigtable:一个结构化数据的分布式存储系统”。就像Bigtable利用了Google文件系统(File System)所提供的分布式数据存储一样,HBase在Hadoop之上提供了类似于Bigtable的能力。HBase是Apache的Hadoop项目的子项目。HBase不同于一般的关系数据库,它是一个适合于非结构化数据存储的数据库。另一个不同的是HBase基于列的而不是基于行的模式。

hbase表结构


列簇1 列簇2(建议1-3个列簇)
列a 列b... 列a 列b...
列簇会用于做索引,一般列簇1,2用于存放常用的筛选用字段,列簇3用于存放内容字段
在下面的代码示例中,一共有两个列簇,familyName1和familyName2
familyName1中存放了三个用于频繁查询筛选的字段:ab,dt,hb
familyName2中存放了整个数据结构的json化字符串

hbase操作 代码示例

1、创建表

2、增/改

public void put(String tableName, Object item) {
        if (item== null) {
            LOG.error("[HBase] itemis null!");
            return;
        }
        // 设置rowkey
        if (item.getid() == null || item.getid().isEmpty()) {
            LOG.error("[HBase] Adding null/empty key!");
            return;
        }

        String ultimateRowKey = getHashedID(item.getid());
        if (ultimateRowKey == null || ultimateRowKey.isEmpty()) {
            LOG.error("[HBase] Adding null/empty hashed key! Original key is " + item.getid());
            return;
        }
        Put put = new Put(Bytes.toBytes(ultimateRowKey));
        // HTabel负责跟记录相关的操作如增删改查等
        Table table = null;
        try {
            table = con.getTable(TableName.valueOf(tableName));
            put.addColumn(Bytes.toBytes(familyName1), Bytes.toBytes("ab"), Bytes.toBytes(item.getAvailable()));
            put.addColumn(Bytes.toBytes(familyName1), Bytes.toBytes("dt"), Bytes.toBytes(item.getDistype()));
            put.addColumn(Bytes.toBytes(familyName1), Bytes.toBytes("hb"), Bytes.toBytes(item.getHotboost()));
            Gson gson = new Gson();
            String value = gson.toJson(item);
            put.addColumn(Bytes.toBytes(familyName2), Bytes.toBytes("js"), Bytes.toBytes(value));
            table.put(put);
        } catch (IOException e) {
            LOG.error("[HBase] Failed to connect to table while adding!  " + e.getMessage());
        } finally {
            try {
                if (table != null)
                    table.close();
            } catch (IOException e) {
                LOG.error("[HBase] Error while closing table " + e.getMessage());
            }
        }
    }

3、删

//按照rowkey进行删除某一行
public void del(String tablename, String rowkey) {
        // 设置rowkey
        if (rowkey == null || rowkey.isEmpty()) {
            LOG.error("[HBase] Adding null/empty key!");
            return;
        }
        String ultimateRowKey = getHashedID(rowkey);
        if (ultimateRowKey == null || ultimateRowKey.isEmpty()) {
            LOG.error("[HBase] Adding null/empty hashed key! Original key is " + rowkey);
            return;
        }
        Table table = null;
        Delete delete = new Delete(Bytes.toBytes(ultimateRowKey));
        try {
            table = con.getTable(TableName.valueOf(tablename));
            table.delete(delete);
        } catch (IOException e) {
            LOG.error("[HBase] Failed to connect to table while del!  " + e.getMessage());
        } finally {
            try {
                if (table != null)
                    table.close();
            } catch (IOException e) {
                LOG.error("[HBase] Error while closing table " + e.getMessage());
            }
        }
    }

4、查

public String get(String tablename, String rowKey) {
        // 先查询索引表
        Table cntTable = null;
        try {
            cntTable = con.getTable(TableName.valueOf(tablename));
            String ultimateRowKey = getHashedID(rowKey);
            if (ultimateRowKey == null || ultimateRowKey.isEmpty()) {
                LOG.error("[HBase] Getting hashed null/empty key! Original key is " + rowKey);
                return null;
            }
            Get get = new Get(Bytes.toBytes(ultimateRowKey));
            Result result = cntTable.get(get);

            String hbaseValue = Bytes.toString(result.getValue(Bytes.toBytes(familyName2), Bytes.toBytes("js")));
            return hbaseValue;
        } catch (IOException e) {
            LOG.error("[HBase] Failed to connect to " + tablename + " while getting!  " + e.getMessage());
            return null;
        } finally {
            try {
                if (cntTable != null)
                    cntTable.close();
            } catch (IOException e) {
                LOG.error("[HBase] Error while closing table " + tablename + e.getMessage());
            }
        }
    }

5、批量写入

public <T> void puts(String tableName, Map<String, Object> items) {
        if (items == null || items.isEmpty()) {
            LOG.error("[HBase] Adding null/empty item map!");
            return;
        }
        int maxSize = 10000;
        Table table = null;
        try {
            table = con.getTable(TableName.valueOf(tableName));
            int eachSize = Math.min(maxSize, items.size());
            List<Put> puts = new ArrayList<Put>(eachSize);
            int handled = 0;
            for (Entry<String, Object> entry : items.entrySet()) {
                String ultimateRowKey = getHashedID(entry.getKey());
                Object value = entry.getValue();
                if (ultimateRowKey == null || ultimateRowKey.isEmpty()) {
                    LOG.error("[HBase] Adding null/empty hashed key! Original key is " + entry.getKey());
                    handled++;
                    continue;
                }
                // System.out.println(ultimateRowKey);
                Put put = new Put(Bytes.toBytes(ultimateRowKey));
                put.addColumn(Bytes.toBytes(familyName1), Bytes.toBytes("ab"), Bytes.toBytes(value .getAb()));
                put.addColumn(Bytes.toBytes(familyName1), Bytes.toBytes("dt"), Bytes.toBytes(value .getDt()));
                put.addColumn(Bytes.toBytes(familyName1), Bytes.toBytes("hb"), Bytes.toBytes(value .getHb()));
                Gson gson = new Gson();
                String valuestr = gson.toJson(value);
                put.addColumn(Bytes.toBytes(familyName2), Bytes.toBytes("js"), Bytes.toBytes(valuestr));
                puts.add(put);
                handled++;
                // 每隔10000,写一次
                if (handled == eachSize) {
                    LOG.info("[HBase] Adding " + eachSize + "rows!");
                    table.put(puts);
                    puts = new ArrayList<Put>(eachSize);
                }
            }
            if (puts.size() > 0)
                table.put(puts);
        } catch (IOException e) {
            LOG.error("[HBase] Error while putting data " + e.getMessage());
        } finally {
            try {
                if (table != null)
                    table.close();
            } catch (IOException e) {
                LOG.error("[HBase] Error while closing table " + e.getMessage());
            }
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,387评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,845评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,091评论 0 246
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,308评论 0 214
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,662评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,795评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,008评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,743评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,466评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,687评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,181评论 1 262
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,531评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,177评论 3 239
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,126评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,902评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,862评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,734评论 2 274

推荐阅读更多精彩内容