3.2.2.2 类: HBaseDao

该类主要用于执行具体的保存数据的操作,rowkey 的生成规则等等。

package com.atguigu.dataconsumer;

import com.atguigu.dataconsumer.util.HBaseUtil;
import com.atguigu.dataconsumer.util.PropertyUtil;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * 该类主要用于执行具体的保存数据的操作,rowkey 的生成规则等等。
 */
public class HBaseDao {
    private String ns = PropertyUtil.getProperty("hbase.namespace");
    private String tableName = PropertyUtil.getProperty("hbase.table.name");
    private String cf = PropertyUtil.getProperty("hbase.cf");
    /**
     * HBase 中的 ns_telecom:calllog表
     */
    private Table table;

    /**
     * 创建命名空间和创建表
     */
    public HBaseDao() {
        // 创建命名空间
        HBaseUtil.createNS(ns);
        // 创建表
        HBaseUtil.createTable(tableName, cf);

        // 获取表对象
        table = HBaseUtil.getTable(tableName);

    }

    /**
     * put 数据到 HBase 表中
     * <p>
     * call1,startTime,call2,duration,flag
     *
     * @param value
     */
    public void put(String value) {
        try {
            String[] split = value.split(",");
            Put put = new Put(HBaseUtil.getRowKey(value));
            byte[] cfBytes = Bytes.toBytes(cf);
            put.addColumn(cfBytes, Bytes.toBytes("call1"), Bytes.toBytes(split[0]));
            put.addColumn(cfBytes, Bytes.toBytes("startTime"), Bytes.toBytes(split[1]));
            put.addColumn(cfBytes, Bytes.toBytes("call2"), Bytes.toBytes(split[2]));
            put.addColumn(cfBytes, Bytes.toBytes("duration"), Bytes.toBytes(split[3]));
            put.addColumn(cfBytes, Bytes.toBytes("flag"), Bytes.toBytes(split[4]));
            table.put(put);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
Copyright © 尚硅谷大数据 2019 all right reserved,powered by Gitbook
该文件最后修订时间: 2019-01-14 05:27:28

results matching ""

    No results matching ""