MapRedece WordCount 代码详析
package com.mvp.hadoop.examples;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
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.GenericOptionsParser;
public class WordCount {
public static class TokenizerMapper extends
Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
// key, value为输入, context是用户代码与MR系统交互的上下文
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
// StringTokenizer将字符串分成一个个的单词
StringTokenizer itr = new StringTokenizer(line);
while (itr.hasMoreTokens()) {
// 将token写入word
word.set(itr.nextToken().toLowerCase());
// 把token当做key
// 由于token出现一次,因此将键值对<token, 1>写入context。 MR框架会将context中的键值对交给Reducer处理
context.write(word, one);
}
}
}
public static class IntSumReducer extends
Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
// key, values为输入, context是用户代码与MR系统交互的上下文
public void reduce(Text key, Iterable<IntWritable> values,
Context context) throws IOException, InterruptedException {
/*
* 注意, map的输出通过context交个reduce之前,要把相同的key的value都合并到一个集合里
* */
int sum = 0;
// 遍历集合里的每一个value
for (IntWritable val : values) {
sum += val.get(); // 每个val=1, 进行累加
}
result.set(sum); // 得到token的词频
// 将<token, 词频>写入context, 由context写到HDFS文件里
context.write(key, new IntWritable(sum));
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration(); // 读取Hadoop配置信息
String[] otherArgs = new GenericOptionsParser(conf, args)
.getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("input & output path BY args\n");
System.exit(2);
}
Job job = new Job(conf, "word_count"); // 创建MR Job
job.setJarByClass(WordCount.class); // 设置启动类
job.setMapperClass(TokenizerMapper.class); // 设置Mapper类
job.setCombinerClass(IntSumReducer.class); // 设置Combiner类
job.setReducerClass(IntSumReducer.class); // 设置Reducer类
job.setOutputKeyClass(Text.class); // 设置输出Key的类型
job.setOutputValueClass(IntWritable.class); // 设置输出值的类型
FileInputFormat.addInputPath(job, new Path(otherArgs[0])); // 设置输入文件目录
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));// 设置输出文件目录
System.exit(job.waitForCompletion(true) ? 0 : 1); // 等待Job完成
}
}