HbaseUtil

package com.nie.k2h.hbase;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
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.Increment;
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.apache.log4j.Logger;

import com.nie.k2h.init.LogLoader;
import com.nie.k2h.order.SKUInfo;

public class HbaseUtils {
    
    private static Logger logger = Logger.getLogger(HbaseUtils.class);
    private static Configuration conf = null;
    static int count=0;
    
    /**
     * 根据行键进行数据查询
     * 
     * @param tableName 表名称,现有表有:sql_gdm_m03_item_sku_da_jss_201405
     * @param rowKey 行键
     * @param columns 返回列过滤(item_first_cate_cd,item_second_cate_cd,
                        item_third_cate_cd,work_post_cd,shop_id,dept_id_1,
                        dept_name_1,dept_id_2,dept_name_2,dept_id_3,dept_name_3)
     * @return
     * @throws IOException
     */
    public static Map<String,String> getResult(HTableInterface table,String cf, String rowKey, String...columns)
            throws IOException {
        Get get = new Get(Bytes.toBytes(rowKey));
        for(String column:columns) {
             get.addColumn(Bytes.toBytes(cf), Bytes.toBytes(column));
        }
        Map<String,String> map = new HashMap<String,String>();
        Result result = table.get(get);
        List<KeyValue> list = result.list();
        if(list!=null){
            for (KeyValue kv : result.list()) {
                map.put(Bytes.toString(kv.getQualifier()), Bytes.toString(kv.getValue()));
            }
        }
        return map;
       // return result;
    }

    /*
     * 遍历查询hbase表
     * 
     * @tableName 表名
     */
    public static void getResultScann(String tableName, String start_rowkey,
            String stop_rowkey) throws IOException {
        Scan scan = new Scan();
        scan.setStartRow(Bytes.toBytes(start_rowkey));
        scan.setStopRow(Bytes.toBytes(stop_rowkey));
        ResultScanner rs = null;
        HTable table = new HTable(conf, Bytes.toBytes(tableName));
        try {
            rs = table.getScanner(scan);
            for (Result r : rs) {
                for (KeyValue kv : r.list()) {
                   logger.error("row:" + Bytes.toString(kv.getRow()));
                   logger.error("family:"
                            + Bytes.toString(kv.getFamily()));
                   logger.error("qualifier:"
                            + Bytes.toString(kv.getQualifier()));
                   logger.error("|" + Bytes.toString(kv.getValue()));
                   logger.error("timestamp:" + kv.getTimestamp());
                    
                }
                logger.error("\n-------------------------------------------");
            }
        } finally {
            rs.close();
            table.close();
        }
    }
    
    
    public static void getItemByItemSkuId(String itemSkuId) {
        try{
//          getResult("cf","sql_gdm_m03_item_sku_da_jss_",itemSkuId);
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }
    
    /*
     * 删除表
     * 
     * @tableName 表名
     */
    public static void deleteTable(String tableName) throws IOException {
        HBaseAdmin admin = new HBaseAdmin(conf);
        admin.disableTable(tableName);
        admin.deleteTable(tableName);
        admin.close();
        System.out.println(tableName + "is deleted!");
    }
    
    /**
     * 获取表名称
     * 
     * @return
     */
    public static String loadTable() {
        HBaseAdmin admin = null;
        logger.debug("++++++++++++++++++++++++++++++start");
        try {
            String prefix = "sql_gdm_m03_item_sku_da_jss_";
            admin = new HBaseAdmin(conf);
            //String [] tables = new String[]{"app_item_sku_sales_statistics_201508","app_item_sku_sales_statistics_201405","app_item_sku_sales_statistics_201403"};
            Pattern p = Pattern.compile("^"+prefix+".\\d+$");
            String [] tables = admin.getTableNames(p);
            //String [] tables = admin.getTableNames();
            if(tables==null||tables.length==0){
                return null;
            }
            /*
            Matcher m = p.matcher("app_item_sku_sales_statistics201508");

            // 查找相应的字符串
            while (m.find()) {
                String tmp = m.group();
                if (!"".equals(tmp)) {
                System.out.duoxi(tmp);
                }
            }*/
            
            int[] suffixs = new int[tables.length];
            for(int i=0;i<tables.length;i++) {
                logger.debug("----------table Name-------------"+tables[i]);
                //if(!tables[i].startsWith(prefix)) continue;
                
                String suffix = tables[i].substring(tables[i].lastIndexOf("_")+1);
                suffixs[i]=Integer.parseInt(suffix);
            }
            Arrays.sort(suffixs);
            logger.debug("++++++++++++++++++++++++++++++end");
            return prefix+suffixs[suffixs.length-1];
        }catch(Exception ex) {
            logger.error("获取表异常:",ex);
            return null;
        }finally {
            try {
                admin.close();
            }catch(IOException io) {
                logger.error("关闭表异常:",io);
            }
        }
    }

    
    /*
     * 创建表
     * 
     * @tableName 表名
     * 
     * @family 列族列表
     */
    public static void creatTable(String tableName, String[] family)
            throws Exception {
        HBaseAdmin admin = new HBaseAdmin(conf);
        HTableDescriptor desc = new HTableDescriptor(tableName);
        for (int i = 0; i < family.length; i++) {
            desc.addFamily(new HColumnDescriptor(family[i]));
        }
        if (admin.tableExists(tableName)) {
            logger.error("---table " + tableName + " Exists!---");
            System.exit(0);
        } else {
            admin.createTable(desc);
            logger.debug("---create table " + tableName + " Success!---");
        }
        admin.close();
    }
    
    
    public static void IncrValue(HTableInterface htable,String rowKey,
            String family,String columnArr[],long valueArr[]){
        try{
            htable.setAutoFlush(false);
            Increment inc = new Increment(Bytes.toBytes(rowKey));
            for (int j = 0; j < columnArr.length; j++) {
                inc.addColumn(Bytes.toBytes(family), Bytes.toBytes(columnArr[j]),valueArr[j]);
            }
            htable.increment(inc);
        }catch(Exception e){
            LogLoader.getLog().error("IncrValue error msg",e);
        }
        
    }

    /**
     * 
     * @param tableName
     * @param familyColumn
     * @param rowKey
     * @param columnArr
     * @param time
     * @param valueArr
     * @throws IOException 
     */
    public static boolean addData(HTableInterface htable,String familyColumn,
                String rowKey,String columnArr[],long ts,String valueArr[]) throws IOException{
        Put put=null;
        try{
                    htable.setAutoFlush(false);
                    put = new Put(Bytes.toBytes(rowKey));
                    for (int j = 0; j < columnArr.length; j++) {
                             put.add(Bytes.toBytes(familyColumn),
                                     Bytes.toBytes(columnArr[j]),
                                     ts,Bytes.toBytes(valueArr[j]));
                    }
                    htable.put(put);
                return true;    
        }catch(Exception e){
            System.out.println("error count="+count++);
            return false;
            //LogLoader.getLog().error("addData error msg : "+e.getMessage(),e);
        }
        
    }
    
    public static String getRowKey(long orderId){
        String id= String.valueOf(orderId);
        if(id==null) return null;
        
        StringBuffer buf= new StringBuffer(id).reverse();
        
        while(buf.length()<13){
            buf.append("0");
        }
        
        return buf.toString();
        
    }
    
    public static void main(String[] args) {
        System.out.println(getRowKey(120876300L));
    }
    /**
     * 字符串左补零
     * 
     * @param
     * @return
     */
    public static String getLeftAddZero(String str, int len) {
        len = len - str.length();
        for (int i = 0; i < len; i++) {
            str = "0" + str;
        }
        return str;
    }
    
    
    /**
     * 查询hbase中的sku的信息
     * @param skus
     * @return
     */
    public static Map<String,String> getCityParComRELA(HTableInterface htable) {
        
        ResultScanner rs = null;
        Map<String,String> map = new HashMap<String, String>();
        try {
            
            Scan scan = new Scan();
            
            scan.addColumn(Bytes.toBytes("f"), Bytes.toBytes("centerNum"));
            
                rs = htable.getScanner(scan);
                if(rs != null ) {
                   for(Result r=rs.next();r!=null;r=rs.next()){                      
                      
                       for(KeyValue kv : r.raw()){
                           map.put(Bytes.toString(kv.getRow()),Bytes.toString(kv.getValue()) );
                       }
                      
                   }
                }
        
        } catch(Exception ex) {
            LogLoader.getLog().error("hbase query getCityParComRELA error",ex);
        } 
        return map;
    }
    
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,657评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,889评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,057评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,509评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,562评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,443评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,251评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,129评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,561评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,779评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,902评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,621评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,220评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,838评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,971评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,025评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,843评论 2 354

推荐阅读更多精彩内容

  • 对于全国疫情来说,基本上都希望越早发现越好,然而显示发源地开始捏着鼻子红眼睛的骗自己,说什么都是造谣,直到事态...
    leving阅读 137评论 0 0
  • 才搬家到小红门村,夜晚总能听见好像小孩的夜啼声音。 直到好久以后,才想明白,那黑夜中传来的声音是猫叫。 在东北老家...
    刘迟阅读 400评论 0 1
  • 作为一个现实的文青婊,我爱钱,爱男人,但是我好姑娘。 01你是不是也曾被流言伤害过 贾小姐是位非常美丽的年轻菇凉,...
    太太太阿泰平阅读 590评论 12 11
  • 关住夏日窗, 挡住秋天风。 迎接美妙夜, 梦里回故乡。
    大狗少一阅读 175评论 0 0