【代码样板】HBase一个MapReduce程序ETL

public class SaleOrdersMapReducer extends Configured implements Tool {
	//原表:数据来源
    private final static String ORDERS_TABLE_NAME="ns1:orders";
    //处理后的数据,表需要提前创建
    private final static String HISTORY_ORDERS_TABLE_NAME="orders:history_orders";
    static class ReadOrderMapper extends TableMapper<ImmutableBytesWritable,Put>{
    	//定义基本的不变的字段
        private final static String ORDER_COLUMN_NAME_USER_ID = "user_id";
        private final static String ORDER_COLUMN_NAME_ORDER_ID = "order_id";
        private final static String ORDER_COLUMN_NAME_DATE = "date";
        private final static String HISTORY_ROW_KEY_SEPARATOR = "_";
        private final static byte[] HISTORY_COLUMN_FAMILY= Bytes.toBytes( "order" );

        private ImmutableBytesWritable mapOutput = new ImmutableBytesWritable(  );
        @Override
        protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException {

            //编写专门的方法,转换数据,得到Put对象
            Put put = resultToPut(key,value);
            //输出rowKey
            mapOutput.set( put.getRow() );
            //输出
            context.write( mapOutput,put );
        }

        private Put resultToPut(ImmutableBytesWritable key, Result result) {
            //订单Id
            String orderId = Bytes.toString( key.get() );
            //date,user_id,order_amt
            HashMap<String, String> orderMap = new HashMap<>();
            for (Cell cell:result.rawCells()) {
                String filed = Bytes.toString(CellUtil.cloneQualifier( cell ));
                String value = Bytes.toString(CellUtil.cloneValue( cell ));
                orderMap.put( filed ,value);
            }
            //组合rowKey:userId + orderDate + orderId
            StringBuffer sb = new StringBuffer();
            //reverse(userId)
            sb.append( orderMap.get( ORDER_COLUMN_NAME_USER_ID ) ).reverse();
            sb.append( HISTORY_ROW_KEY_SEPARATOR );
            //date
            sb.append( orderMap.get( ORDER_COLUMN_NAME_DATE )  );
            sb.append( HISTORY_ROW_KEY_SEPARATOR );
            sb.append( orderId );
            //创建Put对象
            Put put = new Put(Bytes.toBytes( sb.toString() ));
            for (Map.Entry<String,String> entry:orderMap.entrySet()) {
                put.addColumn(
                        HISTORY_COLUMN_FAMILY,
                        Bytes.toBytes( entry.getKey() ),
                        Bytes.toBytes( entry.getValue() )   );
            }
            put.addColumn(
                    HISTORY_COLUMN_FAMILY,
                    Bytes.toBytes( ORDER_COLUMN_NAME_ORDER_ID ),
                    Bytes.toBytes( orderId ));
            return put;
        }
    }
    @Override
    public int run(String[] args) throws Exception {
        //读取配置
        Configuration conf = this.getConf();
        //创建Job
        Job job = Job.getInstance( conf, SaleOrdersMapReducer.class.getName() );
        job.setJarByClass( SaleOrdersMapReducer.class );
        //设置Job:
        //input:table  ->map ->output:table
        Scan scan = new Scan();
        // 1 is the default in Scan, which will be bad for MapReduce jobs
        scan.setCaching(500);
        // don't set to true for MR jobs
        scan.setCacheBlocks(false);
        //设置Mapper类和Input table
        TableMapReduceUtil.initTableMapperJob(
                ORDERS_TABLE_NAME,        // input HBase table name
                scan,             // Scan instance to control CF and attribute selection
                ReadOrderMapper.class,   // mapper
                ImmutableBytesWritable.class, // mapper output key,RowKey
                Put.class,        // mapper output value,行内容
                job);
        //设置输出以及Reducer
        TableMapReduceUtil.initTableReducerJob(
                HISTORY_ORDERS_TABLE_NAME,      // output table
                null,             // reducer class
                job);
        job.setNumReduceTasks(0);

        //如果数据量非常大的情况下,不建议使用put方式将数据插入到HBASE表中,
        //而是将数据转成HBASE数据存储的HFile

        //设置MapReduce输出的数据格式
        job.setOutputFormatClass( HFileOutputFormat2.class );

        //往那张表里面写
        HTable table = new HTable( conf, HISTORY_ORDERS_TABLE_NAME );
        HFileOutputFormat2.configureIncrementalLoad( job, table,table.getRegionLocator());

        //设置HFile文件的输出目录
        Path outputPath = new Path(args[0] + System.currentTimeMillis());
        FileOutputFormat.setOutputPath( job, outputPath);

        boolean isSuccess = job.waitForCompletion( true );
        //如果MapReduce运行完成,成功之后,将输出HFile文件 加载到 表中
        if(isSuccess){
            LoadIncrementalHFiles load = new LoadIncrementalHFiles( conf );
            load.doBulkLoad( outputPath, table);
        }
        return isSuccess?0:1;
    }


    public static void main(String[] args) {
        //HBase配置文件
        Configuration conf = HBaseConfiguration.create();
        try {
            //运行job
            int status = ToolRunner.run( conf, new SaleOrdersMapReducer(), args );
            //结束程序
            System.exit( status );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的HBaseMapReduce配置程序的示例代码: ```java import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.mapreduce.TableReducer; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.util.GenericOptionsParser; import java.io.IOException; public class HBaseMapReduceExample { public static class MyMapper extends Mapper<ImmutableBytesWritable, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(ImmutableBytesWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] words = line.split(","); for (String w : words) { word.set(w); context.write(word, one); } } } public static class MyTableReducer extends TableReducer<Text, IntWritable, ImmutableBytesWritable> { public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } context.write(new ImmutableBytesWritable(Bytes.toBytes(key.toString())), new ImmutableBytesWritable(Bytes.toBytes(Integer.toString(sum)))); } } public static void main(String[] args) throws Exception { Configuration conf = HBaseConfiguration.create(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 1) { System.err.println("Usage: HBaseMapReduceExample <tablename>"); System.exit(2); } String tableName = otherArgs[0]; Scan scan = new Scan(); Job job = Job.getInstance(conf, "HBaseMapReduceExample"); job.setJarByClass(HBaseMapReduceExample.class); TableMapReduceUtil.initTableMapperJob(tableName, scan, MyMapper.class, Text.class, IntWritable.class, job); TableMapReduceUtil.initTableReducerJob(tableName, MyTableReducer.class, job); System.exit(job.waitForCompletion(true) ? 0 : 1); } } ``` 这个程序实现了一个简单的词频统计功能,从 HBase 表中读取数据,将每个单词作为键,出现次数作为值,最终将结果写回 HBase 表中。 需要注意的是,程序中的 `MyMapper` 和 `MyTableReducer` 分别是 Mapper 和 Reducer 的实现类,需要根据实际场景进行修改。同时,程序中的 `tableName` 变量需要替换成实际使用的 HBase 表名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值