MapReduce生成HFile入库到HBase

来源:互联网 发布:linux gcc 版本 编辑:程序博客网 时间:2024/05/22 06:07

一、这种方式有很多的优点:

1. 如果我们一次性入库hbase巨量数据,处理速度慢不说,还特别占用Region资源, 一个比较高效便捷的方法就是使用 “Bulk Loading”方法,即HBase提供的HFileOutputFormat类。

2. 它是利用hbase的数据信息按照特定格式存储在hdfs内这一原理,直接生成这种hdfs内存储的数据格式文件,然后上传至合适位置,即完成巨量数据快速入库的办法。配合mapreduce完成,高效便捷,而且不占用region资源,增添负载。

二、这种方式也有很大的限制:

1. 仅适合初次数据导入,即表内数据为空,或者每次入库表内都无数据的情况。

2. HBase集群与Hadoop集群为同一集群,即HBase所基于的HDFS为生成HFile的MR的集群(额,咋表述~~~)

三、接下来一个demo,简单介绍整个过程。

1. 生成HFile部分

package zl.hbase.mr; import java.io.IOException; import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.hbase.KeyValue;import org.apache.hadoop.hbase.io.ImmutableBytesWritable;import org.apache.hadoop.hbase.mapreduce.HFileOutputFormat;import org.apache.hadoop.hbase.mapreduce.KeyValueSortReducer;import org.apache.hadoop.hbase.mapreduce.SimpleTotalOrderPartitioner;import org.apache.hadoop.hbase.util.Bytes;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.Mapper;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import org.apache.hadoop.util.GenericOptionsParser; import zl.hbase.util.ConnectionUtil; public class HFileGenerator {     public static class HFileMapper extends            Mapper<LongWritable, Text, ImmutableBytesWritable, KeyValue> {        @Override        protected void map(LongWritable key, Text value, Context context)                throws IOException, InterruptedException {            String line = value.toString();            String[] items = line.split(",", -1);            ImmutableBytesWritable rowkey = new ImmutableBytesWritable(                    items[0].getBytes());             KeyValue kv = new KeyValue(Bytes.toBytes(items[0]),                    Bytes.toBytes(items[1]), Bytes.toBytes(items[2]),                    System.currentTimeMillis(), Bytes.toBytes(items[3]));            if (null != kv) {                context.write(rowkey, kv);            }        }    }     public static void main(String[] args) throws IOException,            InterruptedException, ClassNotFoundException {        Configuration conf = new Configuration();        String[] dfsArgs = new GenericOptionsParser(conf, args)                .getRemainingArgs();         Job job = new Job(conf, "HFile bulk load test");        job.setJarByClass(HFileGenerator.class);         job.setMapperClass(HFileMapper.class);        job.setReducerClass(KeyValueSortReducer.class);         job.setMapOutputKeyClass(ImmutableBytesWritable.class);        job.setMapOutputValueClass(Text.class);         job.setPartitionerClass(SimpleTotalOrderPartitioner.class);         FileInputFormat.addInputPath(job, new Path(dfsArgs[0]));        FileOutputFormat.setOutputPath(job, new Path(dfsArgs[1]));         HFileOutputFormat.configureIncrementalLoad(job,                ConnectionUtil.getTable());        System.exit(job.waitForCompletion(true) ? 0 : 1);    }}

生成HFile程序说明:

①. 最终输出结果,无论是map还是reduce,输出部分key和value的类型必须是: < ImmutableBytesWritable, KeyValue>或者< ImmutableBytesWritable, Put>。

②. 最终输出部分,Value类型是KeyValue 或Put,对应的Sorter分别是KeyValueSortReducer或PutSortReducer。

③. MR例子中job.setOutputFormatClass(HFileOutputFormat.class); HFileOutputFormat只适合一次对单列族组织成HFile文件

④. MR例子中HFileOutputFormat.configureIncrementalLoad(job, table);自动对job进行配置。SimpleTotalOrderPartitioner是需要先对key进行整体排序,然后划分到每个reduce中,保证每一个reducer中的的key最小最大值区间范围,是不会有交集的。因为入库到HBase的时候,作为一个整体的Region,key是绝对有序的。

⑤. MR例子中最后生成HFile存储在HDFS上,输出路径下的子目录是各个列族。如果对HFile进行入库HBase,相当于move HFile到HBase的Region中,HFile子目录的列族内容没有了。

2. HFile入库到HBase

package zl.hbase.bulkload; import org.apache.hadoop.fs.Path;import org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles;import org.apache.hadoop.util.GenericOptionsParser; import zl.hbase.util.ConnectionUtil; public class HFileLoader {     public static void main(String[] args) throws Exception {        String[] dfsArgs = new GenericOptionsParser(                ConnectionUtil.getConfiguration(), args).getRemainingArgs();        LoadIncrementalHFiles loader = new LoadIncrementalHFiles(                ConnectionUtil.getConfiguration());        loader.doBulkLoad(new Path(dfsArgs[0]), ConnectionUtil.getTable());    } }

通过HBase中 LoadIncrementalHFiles的doBulkLoad方法,对生成的HFile文件入库。


hbase提供了写的操作,通常,我们可以采用HBase的Shell 客户端或者Java API进行操作。

如果数据量大的话,这两种操作是很费时的。其实如果了解了HBase的数据底层存储的细节的话,HBase的数据存储格式是HFile定义的格式。

批量导入HBase主要分两步:

  • 通过mapreduce在输出目录OutputDir下生成一系列按Store存储结构一样的,存储HFile文件
  • 通过LoadIncrementalHFiles.doBulkLoad把OutputDir里面的数据导入HBase表中
优点
  1. HBase提供了一种直接写hfile文件的类,同时通过类似传统数据库的load把这些文件写进去,不再需要通过客户端或Java API一条一条插进去,
  2. 这些接口简单方便,快捷灵活;
  3. 应用不需要一直去连HBase集群进行RPC multi写,提高mapreduce效率;
  4. HBase集群也相应减少不必要的连接,可以让它去多干些其它的事,效率更加高效,降低HBase集群因为大量并发写而产生不必要的风险。
1. 从HDFS批量导入

在MapReduce里面就把想要的输出成HFileOutputFormat格式的文件,然后通过LoadIncrementalHFiles.doBulkLoad方式就可以load进去即可。例子如下: 

Java代码  收藏代码
  1. Configuration conf = getConf();  
  2. conf.set("hbase.table.name", args[2]);  
  3. // Load hbase-site.xml  
  4. HBaseConfiguration.addHbaseResources(conf);  
  5. Job job = new Job(conf, "HBase Bulk Import Example");  
  6. job.setJarByClass(Mapper2.class);  
  7. job.setMapperClass(Mapper2.class);  
  8. job.setMapOutputKeyClass(ImmutableBytesWritable.class);  
  9. job.setMapOutputValueClass(KeyValue.class);  
  10. job.setInputFormatClass(TextInputFormat.class);  
  11.   
  12. // Auto configure partitioner and reducer  
  13. HTable hTable = new HTable(conf, args[2]);  
  14. HFileOutputFormat.configureIncrementalLoad(job, hTable);  
  15.   
  16. FileInputFormat.addInputPath(job, new Path(args[0]));  
  17. FileOutputFormat.setOutputPath(job, new Path(args[1]));  
  18. job.waitForCompletion(true);  
  19.   
  20. // Load generated HFiles into table  
  21. LoadIncrementalHFiles loader = new LoadIncrementalHFiles(conf);  
  22. loader.doBulkLoad(new Path(args[1]), hTable);  
2. 从MySQL批量导入

这个星期把一些MySQL表导到线上HBase表。这个MySQL表散了100份,在HBase集群未提供向业务使用时,通过Sqoop工具导进HBase表所花费的时间大约32个小时(已串行化),在hbase集群繁忙时,花了10个小时都还没有把一张表导到HBase里面。这是有原因的,Sqoop未实现批量导的功能,它通常是边读边写。

后来自己写了一个从MySQL批量导入HBase的应用程序,每个表导入HBase所需时间平均只需要8分钟。

核心代码如下:

Java代码  收藏代码
  1. HBaseConfiguration.addHbaseResources(conf);  
  2.   
  3. Job job = new Job(conf, "Load_MySQL_" + table + "_to_HBase_" + hbaseTable);  
  4. // 用来读mysql的Mapper  
  5. job.setJarByClass(MysqlMapper.class);  
  6.   
  7. job.setMapperClass(MysqlMapper.class);  
  8. job.setMapOutputKeyClass(ImmutableBytesWritable.class);  
  9. job.setMapOutputValueClass(KeyValue.class);  
  10. //配置DB参数  
  11. DBConfiguration.configureDB(job.getConfiguration(), driver, connect, username, password);  
  12. DataDrivenDBInputFormat.setInput(job, dbWritableClass, query, boundaryQuery);  
  13. DataDrivenDBInputFormat.setInput(job, dbWritableClass, table, conditions, splitBy, columns);  
  14. //设置输出路径  
  15. FileOutputFormat.setOutputPath(job, new Path(tmpTargetDir));  
  16. // 自动设置partitioner和reduce  
  17. HTable hTable = new HTable(conf, hbaseTable);  
  18. HFileOutputFormat.configureIncrementalLoad(job, hTable);  
  19.   
  20. job.waitForCompletion(true);  
  21.   
  22. // 上面JOB运行完后,就把数据批量load到HBASE中  
  23. LoadIncrementalHFiles loader = new LoadIncrementalHFiles(conf);  
  24. loader.doBulkLoad(new Path(tmpTargetDir), hTable);