【hadoop】24.MapReduce-shuffle之合併

簡介

shuffle機制中的合併(Combiner)並非咱們以前將的文件合併,他是一種依附於業務性質的調優手段。這裏回顧一下咱們以前的參考圖java

留意圖中第11步的合併過程,這樣作以後能夠合併一些同key的k-v,節約傳輸的帶寬。apache

  • Combiner是MR程序中Mapper和Reducer以外的一種組件
  • Combiner組件的父類就是Reducer
  • Combiner和reducer的區別在於運行的位置:
    • Combiner是在每個maptask所在的節點運行
    • Reducer是接收全局全部Mapper的輸出結果;

Combiner的意義就是對每個maptask的輸出進行局部彙總,以減少網絡傳輸量。網絡

一、探究Combiner

1.一、自定義Combiner步驟

  1. 自定義一個combiner繼承Reducer,重寫reduce方法便可。
  2. 在驅動類中設置該Combiner。

1.二、優化wordcount

一、添加自定義Combiner類app

package com.zhaoyi.wordcount;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

public class WordCountCombiner extends Reducer<Text, IntWritable, Text, IntWritable> {
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        int count = 0;
        for (IntWritable value : values) {
            count += value.get();
        }
        // 2.輸出該key的總數
        context.write(key, new IntWritable(count));
    }
}

能夠看到Combiner和Reducer的業務代碼一致,區別在於前者(Combiner)是運行在每個MapTask上,然後者是運行在彙總的ReducerTask。ide

二、設置Combineroop

job.setCombinerClass(WordCountCombiner.class);

三、運行,並查看日誌優化

...
Map input records=5
Map output records=72
...
Combine input records=72
Combine output records=51
...

Combine input records爲72,通過咱們的合併以後變爲Combine output records的值,即52行。日誌

1.三、Combiner運用場景

Combiner並非隨便就可使用的,在一些、甚至說大部分狀況下是不能使用這種合併方式。code

可以應用的前提是不能影響最終的業務邏輯,並且,Combiner的輸出kv應該跟reducer的輸入k-v類型要對應起來。blog

例以下面的求平均數的案例

Mapper
3 5 7 ->(3+5+7)/3=5 
2 6 ->(2+6)/2=4
Reducer
(3+5+7+2+6)/5=23/5    不等於    (5+4)/2=9/2

結果顯然是不正確的。

相關文章
相關標籤/搜索