MapReduce是由Google提出的一种编程模型,用于处理和生成大规模数据集。Hadoop的MapReduce是这一编程模型的实现,广泛应用于分布式计算环境中。它将数据处理任务分为两个阶段:Map阶段和Reduce阶段。
Mapper类用于处理输入数据,并生成中间键值对。
public 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);
}
}
}
Reducer类用于汇总中间键值对,并生成最终输出结果。
public 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);
}
}
Driver类用于配置MapReduce作业并提交作业。
public class WordCount {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
准备数据
input.txt
,内容如下:
Hello Hadoop
Hello MapReduce
将数据上传到HDFS
hdfs dfs -mkdir /user/hadoop/input
hdfs dfs -put input.txt /user/hadoop/input/
编译和运行MapReduce程序
WordCount.java
。javac -classpath `hadoop classpath` -d wordcount_classes WordCount.java
jar -cvf wordcount.jar -C wordcount_classes/ .
hadoop jar wordcount.jar WordCount /user/hadoop/input /user/hadoop/output
查看输出结果
hdfs dfs -cat /user/hadoop/output/part-r-00000
输出结果可能如下:
Hadoop 1
Hello 2
MapReduce 1
通过掌握MapReduce的基本概念、编程模型和执行流程,你可以开发高效的分布式数据处理应用,处理大规模数据集。