以下使用Hadoop的经典程序WordCount来说明MapReduce的处理过程,完整代码如下:
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
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.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class WordCount extends Configured implements Tool {
String inputPath = "/path/to/input";
String outputPath = "/path/to/output";
public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
@Override
public int run(String[] arg0) throws Exception {
Job job = Job.getInstance(getConf(), "RunMain");
job.setJarByClass(WordCount.class);
FileInputFormat.addInputPath(job, new Path(inputPath));
FileOutputFormat.setOutputPath(job, new Path(outputPath));
job.setMapperClass(TokenizerMapper.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
return job.waitForCompletion(true) ? 0: 1;
}
public static void main(String[] args) throws Exception {
System.exit(ToolRunner.run(new WordCount(), args));
}
}
输入数据:
Deer Bear River
Car Car River
Deer Car Bear
则以上的程序处理过程如下:
处理过程
上图中从Mapping阶段到Shuffling阶段,是一个网络传输过程,如果数据量非常庞大的时候,就会增加带宽的负担。Hadoop运行用户针对map任务的输出指定一个combiner函数,该函数的输出作为reduce函数的输入。
当以上程序指定reduce作为combiner的时候,在mapping输出到shuffling的阶段,在同一个节点计算的map任务,会首先把相同的单词进行第一次合并,比如上图中的三个map输出中,第二个map会做以下处理才发送到shuffling阶段:
Car,1
Car,1 ==> Car,2
River,1 River,1
这样就会减少从map阶段到reduce阶段的网络传输量。
指定combiner的代码如下:
job.setCombinerClass(IntSumReducer.class);
这里要说明一个问题,以上是使用reduce的代码作为combiner,但是不是每个程序都可以这样处理,只有在reduce的输出与map的输出是一样的情况下,才可以这么使用。