MapReduce原理
通过简单的Mapper和Reducer的抽象提供一个编程模型,可以在一个由几十台上百台PC组成的不可靠集群上并发地,分布式处理大量的数据集,而把并发、分布式(机器间通信)和故障恢复等计算细节隐藏起来。 而Mapper和Reducer的抽象,又是各种各样的复杂数据处理都可以分解为的基本元素。这样,复杂的数据处理可以分为多个Job(包含一个Mapper和一个Reducer)组成的有向无环图(DAG),然后每个Mapper和每个Reducer放在集群上运行,就可以得到结果。
MapReduce的输入和输出都是键值对(key-value)
Mapper 阶段:输入k1,v1, 输出k2,v2
Reducer阶段: 输入k2,v2’, 输出k3,v3
其中V2’是V2的一个集合;
3.2 MapReduce之Shuffle
Hadoop的shuffle过程就是从map端输出到reduce端输入之间的过程,这一段应该是Hadoop中最核心的部分,因为涉及到Hadoop中最珍贵的网络资源,所以shuffle过程中会有很多可以调节的参数,也有很多策略可以研究,http://langyu.iteye.com/blog/992916
Shuffle过程就是从map端输出到reduce端输入之间的过程;是MapReduce的心脏!!!
MAP的输出? 环形缓冲区,默认100M,如果缓冲区数据达到80M,就准备写入磁盘文件。每个溢出到本地磁盘的数据已经分区并且排序(默认字典顺序),这些不同的数据块最后还要合并成一个大的文件(内容已经分区并且排序)
此图有几个分区?三个
WordCount程序:主要是一个mapper,一个reducer,源代码如下:
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> {
// define the constant number ONE
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();
// values are the set of each node or file
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);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: Wordcount <in> <out>");
System.exit(2);
}
Job job = new Job(conf, "Word count");
job.setJarByClass(WordCount.class);
job.setJobName("Word count test");
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(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
配置好eclipse的环境后,打开集群,设置输入输出文件的路径和运行结果截图如下: