MapReduce计算模型

MapReduce计算模型

  • MapReduce两个重要角色:JobTracker和TaskTracker。

MapReduce Job

  • 每个任务初始化一个Job,没个Job划分为两个阶段:Map和Reduce阶段。

  • Map函数接受一个<key, value>形式的输入,输出一个<key, value>形式的中间输出。

  • Hadoop负责将所有的相同中间key值的value集合到一起传递给Reduce函数。

  • Reduce函数接受一个<key, (list of value)>,然后对value集合进行处理并输出结果,输出结果也是<key, value>形式的。


Hadoop 中的 Hello Word 程序

  • wordCount 程序
package com.felix;
import <a href="http://lib.csdn.net/base/17" class='replace_word' title="Java EE知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Java</a>.io.IOException;
import java.util.Iterator;
import java.util.StringTokenizer;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
public class WordCount
{
    public static class Map extends MapReduceBase implements
            Mapper<LongWritable, Text, Text, IntWritable>
    {
        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();
        public void map(LongWritable key, Text value,
                OutputCollector<Text, IntWritable> output, Reporter reporter)
                throws IOException
        {
            String line = value.toString();
            StringTokenizer tokenizer = new StringTokenizer(line);
            while (tokenizer.hasMoreTokens())
            {
                word.set(tokenizer.nextToken());
                output.collect(word, one);
            }
        }
    }
    public static class Reduce extends MapReduceBase implements
            Reducer<Text, IntWritable, Text, IntWritable>
    {
        public void reduce(Text key, Iterator<IntWritable> values,
                OutputCollector<Text, IntWritable> output, Reporter reporter)
                throws IOException
        {
            int sum = 0;
            while (values.hasNext())
            {
                sum += values.next().get();
            }
            output.collect(key, new IntWritable(sum));
        }
    }
    public static void main(String[] args) throws Exception
    {
        JobConf conf = new JobConf(WordCount.class);
        conf.setJobName("wordcount");           //设置一个用户定义的job名称
        conf.setOutputKeyClass(Text.class);    //为job的输出数据设置Key类
        conf.setOutputValueClass(IntWritable.class);   //为job输出设置value类
        conf.setMapperClass(Map.class);         //为job设置Mapper类
        conf.setCombinerClass(Reduce.class);      //为job设置Combiner类
        conf.setReducerClass(Reduce.class);        //为job设置Reduce类
        conf.setInputFormat(TextInputFormat.class);    //为map-reduce任务设置InputFormat实现类
        conf.setOutputFormat(TextOutputFormat.class);  //为map-reduce任务设置OutputFormat实现类
        FileInputFormat.setInputPaths(conf, new Path(args[0]));
        FileOutputFormat.setOutputPath(conf, new Path(args[1]));
        JobClient.runJob(conf);         //运行一个job
    }
}
  • 处理流程:读取文件 -> Map -> 切出其中的单词并标记数目为1,如<word, 1> -> Reduce -> 收集相同key值的value形成<key, list of value> -> 将所有的1加起来 -> 输出<key, value>,即<word, count>

  • 执行过程:

// 初始化
JobConf conf = new JobConf(MyMapre.class);
// 为job命名
conf.setJobName("wordcount");
// 设成供Map处理的<key, value>对
conf.setInputFormat(TestInputFormat.class);
// 设置出输出格式
conf.setOutputFormat(TestOutputFormat.class);
conf.setMapperClass(Map.class);
conf.setReduceClass(Reduce.class);
// 设置输入输出路径
FileInputFormat.setInputPath(conf, new Path(args[0]);
FileOutputFormat.setOutputPath(conf, new Path(args[1]);
  • TextInputFormat中,没一行都会生成一条记录,每条记录表示为<key, value>

  • key值是每个数据的记录在数据分片中的字节偏移量,数据类型是LongWritable

  • value是每行的内容,数据类型是Text

  • Map()函数集成自MapReduceBase

  • 实现Mapper接口,有四种形式的参数(key值类型,输入的value值的类型,输出的key值类型,输出的value值类型)

  • 实现此接口还要实现Map()方法,负责具体的对输入进行操作

  • 本例中,首先以空格为单位进行切片,然后使用OutputCollect收集输出的<word, 1>

  • Reduce()与Map()相似

  • 本例中,输入<Text, IntWritable>,输出<Text, IntWritable>


运行MapReduce程序

  • Eclipse中运行

  • 命令行运行:

// 建立FirstJar
mkdir FirstJar
// 编译生成.class文件,存放到FirstJar中
javac -classpath ~/hadoop/hadoop-core.jar -d FirstJar
WordCount.java
jav -cvf wordcount.jar -C FirstJar/.
  • 上传文件到hadoop
hadoop fs -mkdir ...
hadoop fs -put ...
  • 运行
hadoop jar wordcount.jar WordCount input output

新的API

  • 新的程序:
import java.io.IOException;
import java.util.Iterator;
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 {
        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();

        protected void map(Object key, Text value, Context context)
                throws IOException, InterruptedException {
            StringTokenizer tokenizer = new StringTokenizer(value.toString());
            while (tokenizer.hasMoreTokens()) {
                word.set(tokenizer.nextToken());
                context.write(word, one);
            }
        }
    }

    public static class IntSumReducer extends
            Reducer {
        private IntWritable result = new IntWritable();

        protected void reduce(Text key, Iterator values,
                Context context) throws IOException, InterruptedException {
            int sum = 0;
            while (values.hasNext()) {
                sum += values.next().get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }

    public static void main(String[] args) throws IOException,
            InterruptedException, ClassNotFoundException {

        // section 1
        Configuration conf = new Configuration();
        String[] otherArgs = new GenericOptionsParser(conf, args)
                .getRemainingArgs();
        if (otherArgs.length != 2) {
            System.err.println("Usage : wordcount ");
            System.exit(2);
        }
        Job job = new Job(conf, "wordcount");
        job.setJarByClass(WordCount.class);

        // section2
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        // section3
        job.setMapperClass(TokenizerMapper.class);
        job.setCombinerClass(IntSumReducer.class);

        // section4
        FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));

        // section5
        System.exit(job.waitForCompletion(true) ? 0 : 1);

    }
}
  • 新的API中,Mapper和Reducer不是接口而是抽象类。Map和Reduce函数竭诚Mapper和Reducer抽象类。

  • 更加频繁的用context对象,进行MapReduce间的通信,MapContext充当OutputCollector和Reporter。

  • Job的配置统一由Configuration来完成,不必额外的使用JobConf对守护进程进行配置。

  • 由Job来负责Job的控制,而不是JobClient。


MapReduce的数据流和控制流

  • 简单的控制流:
    JobTracker调度任务给TaskTracker,TaskTracker执行任务时,返回进度报告。JobTracker记录进度的进行状况,如果某个TaskTracker上的任务失败,那么JobTracker会把这个任务分配给另一台TaskTracker。

MapReduce优化

  • MapReduce任务擅长处理少量的大数据,而在处理大量的小数据时,MapReduce性能会逊色不少。

  • 当以个Map任务的运行时间在一分钟左右比较合适。

  • MapReduce任务槽:Map/Reduce任务槽就是这个集群能够同事运行的Map/Reduce任务的最大数量。


posted @ 2016-08-03 18:48  英吹斯汀ING  阅读(577)  评论(0编辑  收藏  举报