Hadoop之MapReduce程序分析

版权声明:本文为博主原创文章,未经博主同意不得转载。

https://blog.csdn.net/wangloveall/article/details/28578979

摘要:Hadoop之MapReduce程序包含三个部分:Mapper,Reducer和作业运行。

本文介绍和分析MapReduce程序三部分结构。

关键词:MapReduce   Mapper  Reducer   作业运行

MapReduce程序包含三个部分,各自是Mapper。Reducer和作业运行。

Mapper

一个类要充当Mapper须要继承MapReduceBase并实现Mapper接口。

Mapper接口负责数据处理阶段。它採用形式为Mapper<K1,V1,K2,V2>的Java泛型。

这里的键类和值类分别实现了WritableComparable接口和Writable接口。

Mapper接口仅仅有一个map()方法,用于处理一个单独的键值对。

map()方法形式例如以下。

public  void map(K1  key,  V1  value,  OutputCollector<K2,V2> output ,Reporter reporter  ) throws   IOException

或者

public  void map(K1  key, V1 value,  Context  context) throws  IOException, InterruptedException 

该函数处理一个给定的键/值对(K1, V1)。生成一个键/值对(K2, V2)的列表(该列表也可能为空)。

Hadoop提供的一些实用的Mapper实现,包含IdentityMapper。InverseMapper,RegexMapper和TokenCountMapper等。

Reducer

一个类要充当Reducer须要继承MapReduceBase并实现Reducer接口。

Reduce接口有一个reduce()方法。其形式例如以下。

public  void reduce(K2  key , Iterator<V2> value, OutputCollector<K3, V3>  output,  Reporter reporter) throws  IOException

或者 

public  void  reduce(K2  key, Iterator<V2> value,  Context context)  throws  IOException, InterruptedException

当Reducer任务接受来自各个Mapper的输出时。它依据键/值对中的键对输入数据进行排序,而且把具有同样键的值进行归并,然后调用reduce()函数,通过迭代处理那些与指定键相关联的值,生成一个列表<K3, V3>(可能为空)。

Hadoop提供一些实用Reducer实现,包含IdentityReducer和LongSumReducer等。

作业运行

在run()方法中。通过传递一个配置好的作业给JobClient.runJob()以启动MapReduce作业。

run()方法里,须要为每一个作业定制基本參数,包含输入路径、输出路径、Mapper类和Reducer类。

一个典型的MapReduce程序基本模型例如以下。

public  class  MyJob extends  Configured implements Tool {

       /*  mapreduce程序中Mapper*/

      public static class MapClass extends MapReduceBase                                   implements   Mapper<Text,Text,Text,Text>  {

            public void map(Text  key,   Text value,   

                                                  OutputCollector<Text,Text> output,

                                                 Reporter  reporter) throws IOException {

                                                       //加入Mapper内处理代码

                                                }

      }

      /*MapReduce程序中Reducer*/

      public  static class  Reduce  extends  MapReduceBase  

      implements  Reducer<Text,Text,Text,Text>   {

               public void reduce<Text key,Iterator<Text> values,

               OutputCollector<Text,Text>output,Reporter reporter)

             throws IOException  {

                 //加入Reducer内处理代码

            }

      }

      /*MapReduce程序中作业运行*/

      public int  run(String[] args) throws Exception {

        //加入作业运行代码

         return 0;

      }

}

Resource:

1  http://www.wangluqing.com/2014/03/hadoop-mapreduce-program-analyze/ 

2  參考《Hadoop实战》第四章 编写MapReduce基础程序


posted @ 2019-05-20 21:37  mqxnongmin  阅读(179)  评论(0编辑  收藏  举报