首頁技術文章正文

怎樣創(chuàng)建和使用Combiner組件?

更新時間:2020-11-12 來源:黑馬程序員 瀏覽量:

  在Map階段輸出可能會產(chǎn)生大量相同的數(shù)據(jù),例如……,勢必會降低Reduce聚合階段的執(zhí)行效率。Combiner組件的作用就是對Map階段的輸出的重復數(shù)據(jù)先做一次合并計算,然后把新的(key,value)作為Reduce階段的輸入。圖1描述的就是Combiner組件對Map的合并操作。

1605174126205_1.gif

圖1 Combiner組件的合并操作

  Combiner組件是MapReduce程序中的一種重要的組件,如果想自定義Combiner,我們需要繼承Reducer類,并且重寫reduce()方法。接下來,我們針對詞頻統(tǒng)計案例編寫一個Combiner組件,演示如何創(chuàng)建和使用Combiner組件,具體代碼,如文件所示。

  文件 WordCountCombiner.java

  import java.io.IOException;

   import org.apache.hadoop.io.IntWritable;

   import org.apache.hadoop.io.Text;

   import org.apache.hadoop.mapreduce.Reducer;

   public class WordCountCombiner extends Reducer<Text, 

                     IntWritable, Text, IntWritable> {

     @Override

     protected void reduce(Text key, Iterable<IntWritable> values,

         Reducer<Text, IntWritable, Text, IntWritable>.Context 

             context) throws IOException, InterruptedException {

      // 局部匯總

      int count = 0;

      for (IntWritable v : values) {

        count += v.get();

      }

      context.write(key, new IntWritable(count));

    }

  }

  文件是自定義Combiner類,它的作用就是將key相同的單詞匯總(這與WordCountReducer類的reduce()方法相同,也可以直接指定WordCountReducer作為Combiner類),另外還需要在主運行類中為Job設置Combiner組件即可,具體代碼如下:

  wcjob.setCombinerClass(WordCountCombiner.class);

  小提示:

  執(zhí)行MapReduce程序,添加與不添加Combiner結果是一致的。通俗的講,無論調(diào)用多少次Combiner,Reduce的輸出結果都是一樣的,因為Combiner組件不允許改變業(yè)務邏輯。

猜你喜歡

MapReduce程序怎樣設置模式才能在在本地運行 

InputFormat接口的定義代碼如何設置 


分享到:
在線咨詢 我要報名
和我們在線交談!