Hadoop MapReduce处理海量小文件:自定义InputFormat和RecordReader

来源:互联网 发布:sd卡照片数据恢复 编辑:程序博客网 时间:2024/05/06 00:57

一般来说,基于Hadoop的MapReduce框架来处理数据,主要是面向海量大数据,对于这类数据,Hadoop能够使其真正发挥其能力。对于海量小文件,不是说不能使用Hadoop来处理,只不过直接进行处理效率不会高,而且海量的小文件对于HDFS的架构设计来说,会占用NameNode大量的内存来保存文件的元数据(Bookkeeping)。另外,由于文件比较小,我们是指远远小于HDFS默认Block大小(64M),比如1k~2M,都很小了,在进行运算的时候,可能无法最大限度地充分Locality特性带来的优势,导致大量的数据在集群中传输,开销很大。
但是,实际应用中,也存在类似的场景,海量的小文件的处理需求也大量存在。那么,我们在使用Hadoop进行计算的时候,需要考虑将小数据转换成大数据,比如通过合并压缩等方法,可以使其在一定程度上,能够提高使用Hadoop集群计算方式的适应性。Hadoop也内置了一些解决方法,而且提供的API,可以很方便地实现。
下面,我们通过自定义InputFormat和RecordReader来实现对海量小文件的并行处理。
基本思路描述如下:
在Mapper中将小文件合并,输出结果的文件中每行由两部分组成,一部分是小文件名称,另一部分是该小文件的内容。

编程实现

我们实现一个WholeFileInputFormat,用来控制Mapper的输入规格,其中对于输入过程中处理文本行的读取使用的是自定义的WholeFileRecordReader。当Map任务执行完成后,我们直接将Map的输出原样输出到HDFS中,使用了一个最简单的IdentityReducer。
现在,看一下我们需要实现哪些内容:

  1. 读取每个小文件内容的WholeFileRecordReader
  2. 定义输入小文件的规格描述WholeFileInputFormat
  3. 用来合并小文件的Mapper实现WholeSmallfilesMapper
  4. 输出合并后的文件Reducer实现IdentityReducer
  5. 配置运行将多个小文件合并成一个大文件

接下来,详细描述上面的几点内容。

  • WholeFileRecordReader类

输入的键值对类型,对小文件,每个文件对应一个InputSplit,我们读取这个InputSplit实际上就是具有一个Block的整个文件的内容,将整个文件的内容读取到BytesWritable,也就是一个字节数组。

01package org.shirdrn.kodz.inaction.hadoop.smallfiles.whole;
02 
03import java.io.IOException;
04 
05import org.apache.hadoop.fs.FSDataInputStream;
06import org.apache.hadoop.fs.FileSystem;
07import org.apache.hadoop.fs.Path;
08import org.apache.hadoop.io.BytesWritable;
09import org.apache.hadoop.io.IOUtils;
10import org.apache.hadoop.io.NullWritable;
11import org.apache.hadoop.mapreduce.InputSplit;
12import org.apache.hadoop.mapreduce.JobContext;
13import org.apache.hadoop.mapreduce.RecordReader;
14import org.apache.hadoop.mapreduce.TaskAttemptContext;
15import org.apache.hadoop.mapreduce.lib.input.FileSplit;
16 
17public classWholeFileRecordReader extendsRecordReader<NullWritable, BytesWritable> {
18 
19    privateFileSplit fileSplit;
20    privateJobContext jobContext;
21    privateNullWritable currentKey = NullWritable.get();
22    privateBytesWritable currentValue;
23    privateboolean finishConverting = false;
24 
25    @Override
26    publicNullWritable getCurrentKey() throwsIOException, InterruptedException {
27        returncurrentKey;
28    }
29 
30    @Override
31    publicBytesWritable getCurrentValue() throwsIOException, InterruptedException {
32        returncurrentValue;
33    }
34 
35    @Override
36    publicvoid initialize(InputSplit split, TaskAttemptContext context)throws IOException, InterruptedException {
37        this.fileSplit = (FileSplit) split;
38        this.jobContext = context;
39        context.getConfiguration().set("map.input.file", fileSplit.getPath().getName());
40    }
41 
42    @Override
43    publicboolean nextKeyValue() throwsIOException, InterruptedException {
44        if(!finishConverting) {
45            currentValue =new BytesWritable();
46            intlen = (int) fileSplit.getLength();
47            byte[] content =new byte[len];
48            Path file = fileSplit.getPath();
49            FileSystem fs = file.getFileSystem(jobContext.getConfiguration());
50            FSDataInputStream in =null;
51            try{
52                in = fs.open(file);
53                IOUtils.readFully(in, content,0, len);
54                currentValue.set(content,0, len);
55            }finally {
56                if(in != null) {
57                    IOUtils.closeStream(in);
58                }
59            }
60            finishConverting =true;
61            returntrue;
62        }
63        returnfalse;
64    }
65 
66    @Override
67    publicfloat getProgress() throwsIOException {
68        floatprogress = 0;
69        if(finishConverting) {
70            progress =1;
71        }
72        returnprogress;
73    }
74 
75    @Override
76    publicvoid close() throwsIOException {
77        // TODO Auto-generated method stub
78 
79    }
80}

实现RecordReader接口,最核心的就是处理好迭代多行文本的内容的逻辑,每次迭代通过调用nextKeyValue()方法来判断是否还有可读的文本行,直接设置当前的Key和Value,分别在方法getCurrentKey()和getCurrentValue()中返回对应的值。
另外,我们设置了”map.input.file”的值是文件名称,以便在Map任务中取出并将文件名称作为键写入到输出。

  • WholeFileInputFormat类
01package org.shirdrn.kodz.inaction.hadoop.smallfiles.whole;
02 
03import java.io.IOException;
04 
05import org.apache.hadoop.io.BytesWritable;
06import org.apache.hadoop.io.NullWritable;
07import org.apache.hadoop.mapreduce.InputSplit;
08import org.apache.hadoop.mapreduce.RecordReader;
09import org.apache.hadoop.mapreduce.TaskAttemptContext;
10import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
11 
12public classWholeFileInputFormat extendsFileInputFormat<NullWritable, BytesWritable> {
13 
14    @Override
15    publicRecordReader<NullWritable, BytesWritable> createRecordReader(InputSplit split, TaskAttemptContext context)throws IOException, InterruptedException {
16        RecordReader<NullWritable, BytesWritable> recordReader =new WholeFileRecordReader();
17        recordReader.initialize(split, context);
18        returnrecordReader;
19    }
20}

这个类实现比较简单,继承自FileInputFormat后需要实现createRecordReader()方法,返回用来读文件记录的RecordReader,直接使用前面实现的WholeFileRecordReader创建一个实例,然后调用initialize()方法进行初始化。

  • WholeSmallfilesMapper
01package org.shirdrn.kodz.inaction.hadoop.smallfiles.whole;
02 
03import java.io.IOException;
04 
05import org.apache.hadoop.io.BytesWritable;
06import org.apache.hadoop.io.NullWritable;
07import org.apache.hadoop.io.Text;
08import org.apache.hadoop.mapreduce.Mapper;
09 
10public classWholeSmallfilesMapper extendsMapper<NullWritable, BytesWritable, Text, BytesWritable> {
11 
12    privateText file = new Text();
13 
14    @Override
15    protectedvoid map(NullWritable key, BytesWritable value, Context context)throws IOException, InterruptedException {
16        String fileName = context.getConfiguration().get("map.input.file");
17        file.set(fileName);
18        context.write(file, value);
19    }
20}
  • IdentityReducer类
01package org.shirdrn.kodz.inaction.hadoop.smallfiles;
02 
03import java.io.IOException;
04 
05import org.apache.hadoop.mapreduce.Reducer;
06 
07public classIdentityReducer<Text, BytesWritable> extendsReducer<Text, BytesWritable, Text, BytesWritable> {
08 
09    @Override
10    protectedvoid reduce(Text key, Iterable<BytesWritable> values, Context context)throws IOException, InterruptedException {
11        for(BytesWritable value : values) {
12            context.write(key, value);
13        }
14    }
15}

这个是Reduce任务的实现,只是将Map任务的输出原样写入到HDFS中。

  • WholeCombinedSmallfiles
01package org.shirdrn.kodz.inaction.hadoop.smallfiles.whole;
02 
03import java.io.IOException;
04 
05import org.apache.hadoop.conf.Configuration;
06import org.apache.hadoop.fs.Path;
07import org.apache.hadoop.io.BytesWritable;
08import org.apache.hadoop.io.Text;
09import org.apache.hadoop.mapreduce.Job;
10import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
11import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
12import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
13import org.apache.hadoop.util.GenericOptionsParser;
14import org.shirdrn.kodz.inaction.hadoop.smallfiles.IdentityReducer;
15 
16public classWholeCombinedSmallfiles {
17 
18    publicstatic void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
19 
20        Configuration conf =new Configuration();
21        String[] otherArgs =new GenericOptionsParser(conf, args).getRemainingArgs();
22        if(otherArgs.length != 2) {
23            System.err.println("Usage: conbinesmallfiles <in> <out>");
24            System.exit(2);
25        }
26 
27        Job job =new Job(conf, "combine smallfiles");
28 
29        job.setJarByClass(WholeCombinedSmallfiles.class);
30        job.setMapperClass(WholeSmallfilesMapper.class);
31        job.setReducerClass(IdentityReducer.class);
32 
33        job.setMapOutputKeyClass(Text.class);
34        job.setMapOutputValueClass(BytesWritable.class);
35        job.setOutputKeyClass(Text.class);
36        job.setOutputValueClass(BytesWritable.class);
37 
38        job.setInputFormatClass(WholeFileInputFormat.class);
39        job.setOutputFormatClass(SequenceFileOutputFormat.class);
40 
41        job.setNumReduceTasks(5);
42 
43        FileInputFormat.addInputPath(job,new Path(otherArgs[0]));
44        FileOutputFormat.setOutputPath(job,new Path(otherArgs[1]));
45 
46        intexitFlag = job.waitForCompletion(true) ?0 : 1;
47        System.exit(exitFlag);
48    }
49 
50}
这是是程序的入口,主要是对MapReduce任务进行配置,只需要设置好对应的配置即可。我们设置了5个Reduce任务,最终会有5个输出结果文件。
这里,我们的Reduce任务执行的输出格式为SequenceFileOutputFormat定义的,就是SequenceFile,二进制文件
1 0