MapReduce的数据流程、执行流程

MapReduce的数据流程:

    1. 预先加载本地的输入文件
    2. 经过MAP处理产生中间结果
    3. 经过shuffle程序将相同key的中间结果分发到同一节点上处理
    4. Recude处理产生结果输出
    5. 将结果输出保存在hdfs上

MAP

在map阶段,使用job.setInputFormatClass定义的InputFormat将输入的数据集分割成小数据块splites, 
同时InputFormat提供一个RecordReder的实现。默认的是TextInputFormat, 
他提供的RecordReder会将文本的一行的偏移量作为key,这一行的文本作为value。 
这就是自定义Map的输入是<LongWritable, Text>的原因。 
然后调用自定义Map的map方法,将一个个<LongWritable, Text>对输入给Map的map方法。

最终是按照自定义的MAP的输出key类,输出class类生成一个List<MapOutputKeyClass, MapOutputValueClass>。

Partitioner

在map阶段的最后,会先调用job.setPartitionerClass设置的类对这个List进行分区, 
每个分区映射到一个reducer。每个分区内又调用job.setSortComparatorClass设置的key比较函数类排序。

可以看到,这本身就是一个二次排序。 
如果没有通过job.setSortComparatorClass设置key比较函数类,则使用key的实现的compareTo方法。

Shuffle:

将每个分区根据一定的规则,分发到reducer处理

Sort

在reduce阶段,reducer接收到所有映射到这个reducer的map输出后, 
也是会调用job.setSortComparatorClass设置的key比较函数类对所有数据对排序。 
然后开始构造一个key对应的value迭代器。这时就要用到分组, 
使用jobjob.setGroupingComparatorClass设置的分组函数类。只要这个比较器比较的两个key相同, 
他们就属于同一个组,它们的value放在一个value迭代器

Reduce 
最后就是进入Reducer的reduce方法,reduce方法的输入是所有的(key和它的value迭代器)。 
同样注意输入与输出的类型必须与自定义的Reducer中声明的一致。

一个更为详细的流程图

具体的例子:

是hadoop mapreduce example中的例子,自己改写了一下并加入的注释

import java.io.DataInput;
import java.io.DataOutput;
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.LongWritable;
import org.apache.hadoop.io.RawComparator;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.util.GenericOptionsParser;

import com.catt.cdh.mr.example.SecondarySort2.FirstPartitioner;
import com.catt.cdh.mr.example.SecondarySort2.Reduce;

/**
 * This is an example Hadoop Map/Reduce application.
 * It reads the text input files that must contain two integers per a line.
 * The output is sorted by the first and second number and grouped on the
 * first number.
 *
 * To run: bin/hadoop jar build/hadoop-examples.jar secondarysort
 * <i>in-dir</i> <i>out-dir</i>
 */
public class SecondarySort {

	/**
	 * Define a pair of integers that are writable.
	 * They are serialized in a byte comparable format.
	 */
	public static class IntPair implements WritableComparable<IntPair> {
		private int first = 0;
		private int second = 0;

		/**
		 * Set the left and right values.
		 */
		public void set(int left, int right) {
			first = left;
			second = right;
		}

		public int getFirst() {
			return first;
		}

		public int getSecond() {
			return second;
		}

		/**
		 * Read the two integers.
		 * Encoded as: MIN_VALUE -> 0, 0 -> -MIN_VALUE, MAX_VALUE-> -1
		 */
		@Override
		public void readFields(DataInput in) throws IOException {
			first = in.readInt() + Integer.MIN_VALUE;
			second = in.readInt() + Integer.MIN_VALUE;
		}

		@Override
		public void write(DataOutput out) throws IOException {
			out.writeInt(first - Integer.MIN_VALUE);
			out.writeInt(second - Integer.MIN_VALUE);
		}

		@Override
		// The hashCode() method is used by the HashPartitioner (the default
		// partitioner in MapReduce)
		public int hashCode() {
			return first * 157 + second;
		}

		@Override
		public boolean equals(Object right) {
			if (right instanceof IntPair) {
				IntPair r = (IntPair) right;
				return r.first == first && r.second == second;
			} else {
				return false;
			}
		}

		/** A Comparator that compares serialized IntPair. */
		public static class Comparator extends WritableComparator {
			public Comparator() {
				super(IntPair.class);
			}

			// 针对key进行比较,调用多次
			public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2,
					int l2) {
				return compareBytes(b1, s1, l1, b2, s2, l2);
			}
		}

		static {
			// 注意:如果不进行注册,则使用key.compareTo方法进行key的比较
			// register this comparator
			WritableComparator.define(IntPair.class, new Comparator());
		}

		// 如果不注册WritableComparator,则使用此方法进行key的比较
		@Override
		public int compareTo(IntPair o) {
			if (first != o.first) {
				return first < o.first ? -1 : 1;
			} else if (second != o.second) {
				return second < o.second ? -1 : 1;
			} else {
				return 0;
			}
		}
	}

	/**
	 * Partition based on the first part of the pair.
	 */
	public static class FirstPartitioner extends
			Partitioner<IntPair, IntWritable> {
		@Override
		public int getPartition(IntPair key, IntWritable value,
				int numPartitions) {
			return Math.abs(key.getFirst() * 127) % numPartitions;
		}
	}

	/**
	 * Compare only the first part of the pair, so that reduce is called once
	 * for each value of the first part.
	 */
	public static class FirstGroupingComparator implements
			RawComparator<IntPair> {

		// 针对key调用,调用多次
		@Override
		public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
			return WritableComparator.compareBytes(b1, s1, Integer.SIZE / 8,
					b2, s2, Integer.SIZE / 8);
		}

		// 没有监控到被调用,不知道有什么用
		@Override
		public int compare(IntPair o1, IntPair o2) {
			int l = o1.getFirst();
			int r = o2.getFirst();
			return l == r ? 0 : (l < r ? -1 : 1);
		}
	}

	/**
	 * Read two integers from each line and generate a key, value pair
	 * as ((left, right), right).
	 */
	public static class MapClass extends
			Mapper<LongWritable, Text, IntPair, IntWritable> {

		private final IntPair key = new IntPair();
		private final IntWritable value = new IntWritable();

		@Override
		public void map(LongWritable inKey, Text inValue, Context context)
				throws IOException, InterruptedException {
			StringTokenizer itr = new StringTokenizer(inValue.toString());
			int left = 0;
			int right = 0;
			if (itr.hasMoreTokens()) {
				left = Integer.parseInt(itr.nextToken());
				if (itr.hasMoreTokens()) {
					right = Integer.parseInt(itr.nextToken());
				}
				key.set(left, right);
				value.set(right);
				context.write(key, value);
			}
		}
	}

	/**
	 * A reducer class that just emits the sum of the input values.
	 */
	public static class Reduce extends
			Reducer<IntPair, IntWritable, Text, IntWritable> {
		private static final Text SEPARATOR = new Text(
				"------------------------------------------------");
		private final Text first = new Text();

		@Override
		public void reduce(IntPair key, Iterable<IntWritable> values,
				Context context) throws IOException, InterruptedException {
			context.write(SEPARATOR, null);
			first.set(Integer.toString(key.getFirst()));
			for (IntWritable value : values) {
				context.write(first, value);
			}
		}
	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		String[] ars = new String[] { "hdfs://data2.kt:8020/test/input",
				"hdfs://data2.kt:8020/test/output" };
		conf.set("fs.default.name", "hdfs://data2.kt:8020/");

		String[] otherArgs = new GenericOptionsParser(conf, ars)
				.getRemainingArgs();
		if (otherArgs.length != 2) {
			System.err.println("Usage: secondarysort <in> <out>");
			System.exit(2);
		}
		Job job = new Job(conf, "secondary sort");
		job.setJarByClass(SecondarySort.class);
		job.setMapperClass(MapClass.class);

		// 不再需要Combiner类型,因为Combiner的输出类型<Text,
		// IntWritable>对Reduce的输入类型<IntPair, IntWritable>不适用
		// job.setCombinerClass(Reduce.class);
		// Reducer类型
		job.setReducerClass(Reduce.class);
		// 分区函数
		job.setPartitionerClass(FirstPartitioner.class);
		// 设置setSortComparatorClass,在partition后,
		// 每个分区内又调用job.setSortComparatorClass设置的key比较函数类排序
		// 另外,在reducer接收到所有映射到这个reducer的map输出后,
		// 也是会调用job.setSortComparatorClass设置的key比较函数类对所有数据对排序
		// job.setSortComparatorClass(GroupingComparator2.class);
		// 分组函数

		job.setGroupingComparatorClass(FirstGroupingComparator.class);

		// the map output is IntPair, IntWritable
		// 针对自定义的类型,需要指定MapOutputKeyClass
		job.setMapOutputKeyClass(IntPair.class);
		// job.setMapOutputValueClass(IntWritable.class);

		// the reduce output is Text, IntWritable
		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);
	}

}
时间: 2024-08-28 07:43:44

MapReduce的数据流程、执行流程的相关文章

MapReduce V1:MapTask执行流程分析

我们基于Hadoop 1.2.1源码分析MapReduce V1的处理流程. 在文章<MapReduce V1:TaskTracker设计要点概要分析>中我们已经了解了org.apache.hadoop.mapred.Child启动的基本流程,在Child VM启动的过程中会运行MapTask,实际是运行用户编写的MapReduce程序中的map方法中的处理逻辑,我们首先看一下,在Child类中,Child基于TaskUmbilicalProtocol协议与TaskTracker通信,获取到该

Struts框架之 执行流程 struts.xml 配置详细

1.执行流程 服务器启动:          1. 加载项目web.xml          2. 创建Struts核心过滤器对象, 执行filter  →  init()   struts-default.xml,    核心功能的初始化 struts-plugin.xml,      struts相关插件 struts.xml                 用户编写的配置文件  访问:          3. 用户访问Action, 服务器根据访问路径名称,找对应的aciton配置, 创建

通过一个模拟程序让你明白WCF大致的执行流程

在<通过一个模拟程序让你明白ASP.NET MVC是如何运行的>一文中我通过一个普通的ASP.NET Web程序模拟了ASP.NET MVC的执行流程,现在我们通过类似的原理创建一个用于模拟WCF服务端和客户端工作原理的模拟程序.[源代码从这里下载] 目录 一.基本的组件和执行流程 二.创建自定义HttpHandler实现对服务调用请求的处理 三.定义创建WCF组件的工厂 四.定义HttpModule映射WcfHandler 五.创建自定义的真实代理实现服务的调用 六.定义服务代理工厂 七.服

HBase Filter介绍及执行流程

HBASE过滤器介绍:         所有的过滤器都在服务端生效,叫做谓语下推(predicate push down),这样可以保证被过滤掉的数据不会被传送到客户端.         注意:         基于字符串的比较器,如RegexStringComparator和SubstringComparator,比基于字节的比较器更慢,更消耗资源.因为每次比较时它们都需要将给定的值转化为String.截取字符串子串和正则式的处理也需要花费额外的时间.         过滤器本来的目的是为了筛

PHP扩展开发-执行流程与扩展结构

在开发扩展之前,最好了解下PHP内核的执行流程,PHP大概包括三个方面: SAPI Zend VM 扩展 Zend VM是PHP的虚拟机,与JVM类似,都是各自语言的编译/执行的核心.它们都会把各自的代码先编译为一种中间代码,PHP的通常叫opcode,Java通常叫bytecode,不同的是PHP的opcode直接被Zend VM的执行单元调用对应的C函数执行(PHP7加入了AST,会先生成AST,再生成opcode),不会显示保留下来(可以cache保留),而Java通常是生成class文件

《机器人操作系统ROS原理与应用》——2.3 大数据制度和流程规范

2.3 大数据制度和流程规范 2.3.1 制度和流程规范意义 规范化管理是企业中一项艰巨的且需要持续改进的工作,它是企业各项工作正常有效开展的基础,是企业健康有序发展的有力保障.大数据制度和流程规范作为企业规范化管理的一部分,对于大数据工作的开展至关重要.大数据制度和流程规范建设的意义主要侧重于三个方面: 可以保障企业内部大数据系统和周边业务系统运作的有序化.规范化.流程化和标准化,可以降低沟通成本并提高工作效率,保证最终的工作产出. 可以通过制度性措施界定各事业群.事业部.体系.中心.部门间的

分批读取文件中数据的程序流程及其C代码实现

一.概述 在实际的软件开发项目中,经常需要处理大量的文件.某些文件中包含了相当多的数据记录数,如作者本人参与过的项目中,一个文件中有好几十万条记录.如果一次性将多条记录读入,则会花费大量的处理时间,且占用大量的内存. 为此,要求对于包含大量数据记录的文件进行分批读取操作,即每一轮读取一定数目的数据记录,待将这些记录处理完成之后,再读取下一批数据.本文介绍分批读取文件中数据的程序流程,并给出了C程序实现. 二.总体程序流程 实现分批读取文件中数据的程序流程如图1所示. 图1 实现分批读取文件中数据

轻松学MVC4.0–6 MVC的执行流程

原文 http://www.cnblogs.com/ybst/archive/2012/11/02/2750700.html   MVC在底层和传统的asp.net是一致的,在底层之上,相关流程如下: 1)Global.asax里,MvcApplication对象的Application_Start()事件中,调用 RouteConfig.RegisterRoutes(RouteTable.Routes); 来注册路由规则. 2)RouteConfig.RegisterRoutes()方法里,给

MYSQL执行流程的简单探讨

说到mysql的执行,就不得不说它的执行流程.而它的执行流程又分为标准执行流程和优化后的执行流程. 标准流程 标准流程是SQL执行的标准流程,几乎所有的SQL数据库都是以这个流程作为基础的.那么在联表的时候,他的流程是怎么样的呢? 这里会带入两个专业的名词,笛卡尔积,虚拟表(Virtual Table 简称VT); 笛卡尔积这个说明的篇幅太长,大家可以先google一下,这里就不说明了,而且一般有学过集合的同学,都知道这么一个东西 VT就是虚拟的表,在mysql处理某个问题的时候,它需要一个容器