HBASED—JAVA客户端(二)

封装一个Hbase工具类

public class HbaseUtils {
    /**
     * 获取数据
     * @param result 行数据
     */
    public static void showData(Result result){
        while (result.advance()){
            Cell cell = result.current();
            String row = Bytes.toString(CellUtil.cloneRow(cell));
            String family = Bytes.toString(CellUtil.cloneFamily(cell));
            String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));
            String value = Bytes.toString(CellUtil.cloneValue(cell));
            System.out.println(row+"->"+family+":"+qualifier+"->"+value);
        }
    }
    //获取Hbase的管理对象
    public static Admin getAdmin() throws IOException {
        Connection conn = getHbaseConnection();
        //DDL 和 TOOLS 有关的操作在admin对象中
        Admin admin = conn.getAdmin();
        return admin;
    }

    //获取表对象  可以对表进行DML语言操作
    public static Table getTable(String name) throws IOException {
        Connection conn = getHbaseConnection();
        Table table = conn.getTable(TableName.valueOf(name));
        return table;
    }

    //获取Hbase的连接对象
    public static Connection getHbaseConnection() throws IOException {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","linux01:2181,linux02:2181,linux03:2181");
        Connection conn = ConnectionFactory.createConnection(conf);
        return conn;
    }
}

插入一个属性值

private static void putOneRowOneCell() throws IOException {
        //插入数据
        Table tbUser = HbaseUtils.getTable("tb_user");
        Put put = new Put("0002".getBytes());
        put.addColumn("cf2".getBytes(),  //列族
                "age".getBytes(),  //属性
                "19".getBytes()); //值
        tbUser.put(put);
        tbUser.close();
    }

插入一行多个属性值

private static void putOneRowSomeCell() throws IOException {
        Table tbUser = HbaseUtils.getTable("user");
        Put put = new Put("0001".getBytes());
        put.addColumn("info".getBytes(), "name".getBytes(), "zss".getBytes());
        put.addColumn("info".getBytes(), "age".getBytes(), "18".getBytes());
        put.addColumn("extra".getBytes(), "job".getBytes(), "coder".getBytes());
        tbUser.put(put);
        tbUser.close();
    }

插入多行

/**
     * Put方式不好,一行插入一次,进行一次RPC请求
     * 数据插入到hbase中的本质(将数据以Hfile文件格式存储在HDFS的指定位置)
     * 解决:
     * 1、批次插入  先写到内存中,达到一定大小再插入
     * 2、将大量的静态数据转换成hfile文件  直接存储到指定的hdfs路径下  批量导入
     * 将普通的数据 (大量)  ---->   hfile格式的数据 [MR]
     *      * [MR]: 自定义输入和输出[hfile]  --> 指定路径  *****
     *      * 1)   编写java程序  mapper读数据  处理  reducer 写数据
     *      * 2)   使用shell脚本  *** 操作方便简单
     * @throws IOException
     *
     * 插入多行
     */
    private static void putSomeRows() throws IOException {
        Table user = HbaseUtils.getTable("user");
        Put put1 = new Put(Bytes.toBytes("0002"));
        Put put2 = new Put(Bytes.toBytes("0003"));
        Put put3 = new Put(Bytes.toBytes("0004"));
        List<Put> list = new ArrayList<>();
        list.add(put1);
        list.add(put2);
        list.add(put3);
        user.put(list);
        user.close();
    }

批次插入

private static void mutationInsert() throws IOException {
        Connection conn = HbaseUtils.getHbaseConnection();
        BufferedMutator mutator = conn.getBufferedMutator(TableName.valueOf("user"));
        Put put = new Put(Bytes.toBytes("0002"));
        put.addColumn(Bytes.toBytes("info"),// 列族
                Bytes.toBytes("gender"),//属性
                Bytes.toBytes("M"));//值
        //插入数据
        mutator.mutate(put);
        //将缓存在本地的数据 插入hbase
        /**
         * 和shell客户端的flush不同
         *  shell: flush是将hbase中内存中的数据刷新写到hdfs中
         *     这个flush是将本地的数据刷新到hbase中
         */

        mutator.flush();
        mutator.close();
        conn.close();
    }

创建名称空间

private static void nameSpace() throws IOException {
        Admin admin = HbaseUtils.getAdmin();
        NamespaceDescriptor.Builder nsb = NamespaceDescriptor.create("doit");
        NamespaceDescriptor ns = nsb.build();
        //创建名称空间
        admin.createNamespace(ns);
        //修改名称空间
//        admin.modifyNamespace(ns);
        admin.close();
    }

scan全表

private static void scanAllTable(Table table) throws IOException {
        //多行 多列族 多属性
        Scan scan = new Scan();
        //扫描全表
        ResultScanner results = table.getScanner(scan);
        Iterator<Result> it = results.iterator();
        while (it.hasNext()){
            //Result 行
            Result result = it.next();
            HbaseUtils.showData(result);

        }

    }

扫描行数据

private static void scanWithRow(Table table) throws IOException {
        Scan scan = new Scan();
        //显示前n行
//       scan.setLimit(3);
        //[uid002,uid006)
        scan.withStartRow("uid002".getBytes());
        scan.withStopRow("uid006".getBytes());
        ResultScanner results = table.getScanner(scan);
        Iterator<Result> it = results.iterator();
        while (it.hasNext()){
            Result result = it.next();
            HbaseUtils.showData(result);
        }
    }

扫描一个列族的数据

private static void scanFamily(Table table) throws IOException {
        //user.getScanner(a1 , a2)参数一 列族  参数二属性
        ResultScanner scanner = table.getScanner("info".getBytes());
        Iterator<Result> it = scanner.iterator();
        while (it.hasNext()){
            Result result = it.next();
            HbaseUtils.showData(result);
        }
    }

获取某个属性值

/**
     * 一行
     * 一行的一个列族数据
     * 一行的一个属性
     *
     * @throws Exception
     */
    private static void getCell(Table table) throws IOException {
        Get get = new Get("0001".getBytes());
        get.addColumn("info".getBytes(),"name".getBytes());
        Result result = table.get(get);
        HbaseUtils.showData(result);
    }

删除某个属性值

/**
     * 删除多行  List<Delete></>
     * 删除一行
     * 删除一行的一个列族
     * 删除行属性
     *
     * @throws IOException
     */
    private static void deleteCell(Table table) throws IOException {
        Delete delete = new Delete("0001".getBytes());
        delete.addColumn("extra".getBytes(),"job".getBytes());
        //删除一行
        table.delete(delete);
    }

自增

private static void incr(Table table) throws IOException {
        Increment increment = new Increment("0002".getBytes());
        // 参数三  增加的数据
        increment.addColumn("info".getBytes(),"cnt".getBytes(),1);
        table.increment(increment);
        //获取自增数据的值以后再加上 amount
        long l = table.incrementColumnValue("0002".getBytes(), "info".getBytes(), "cnt".getBytes(), 1);
        System.out.println(l);
    }

获取一个表的所有region

private static void getTableRegions() throws IOException {
        Admin admin = HbaseUtils.getAdmin();      
        List<RegionInfo> regions = admin.getRegions(TableName.valueOf("doit:user"));
        for (RegionInfo region : regions) {
            String encodedName = region.getEncodedName();
            byte[] startKey = region.getStartKey();
            byte[] endKey = region.getEndKey();
            System.out.println(encodedName+"--"+Bytes.toString(startKey)+"--"+Bytes.toString(endKey));
            admin.close();
        }
    }

putDetails

private static void putDetails() {
        // Put  行 列族 属性  值    (列族 属性  值)单元格
        Put put = new Put("rk10001".getBytes());

        // 一行中的多个列族
        List<String>  cfs = new ArrayList<>() ;
        // cf1   Cell1
        // cf1   Cell2
        // cf1   Cell3
        // cf1   Cell4
        NavigableMap<byte[], List<Cell>> familyCellMap = put.getFamilyCellMap();
        Set<Map.Entry<byte[], List<Cell>>> entries = familyCellMap.entrySet();
        // 遍历每个列族
        for (Map.Entry<byte[], List<Cell>> entry : entries) {
            byte[] key = entry.getKey();
            String cf = Bytes.toString(key);
            // 将所有的列族存储在list集合中
            cfs.add(cf) ;
            // 每个列族中所有的单元格
            List<Cell> cells = entry.getValue();
            for (Cell cell : cells) {
                byte[] bytes = CellUtil.cloneQualifier(cell);
                String q = new String(bytes);
                if (q.equals("name")) {}
                byte[] value = CellUtil.cloneValue(cell);

            }
            // 获取单元格的属性

        }
    }

获取某行数据(get)

private static void getRowData() throws IOException {
        //获取表对象 DML
        Table tb_user = HbaseUtils.getTable("tb_user");
        //取一行
        Get get = new Get("0001".getBytes());
        Result result = tb_user.get(get);
        while (result.advance()){
            Cell cell = result.current();
            String row = Bytes.toString(CellUtil.cloneRow(cell));
            String family = Bytes.toString(CellUtil.cloneFamily(cell));
            String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));
            String value = Bytes.toString(CellUtil.cloneValue(cell));
            System.out.println(row+"->"+family+":"+qualifier+"->"+value);
        }
        tb_user.close();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值