MapReduce之Shuffle机制-Combiner合并-07

1combinerMR程序中MapperReducer之外的一种组件

2combiner组件的父类就是Reducer

3combinerreducer的区别在于运行的位置:

Combiner是在每一个maptask所在的节点运行

Reducer是接收全局所有Mapper的输出结果;

4combiner的意义就是对每一个maptask的输出进行局部汇总,以减小网络传输量

注意:combiner能够应用的前提是不能影响最终的业务逻辑,如果做总和的话使用combiner没问题,但是如果做平均数的话,就不行,因为局部求完平均数最后reduce再求平均数的话结果就错了.而且,combiner的输出kv应该跟reducer的输入kv类型要对应起来,combiner的输入是mapper的输出,combiner的输出是reduce的输入.

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

自定义combiner,在案例1的基础上操作https://blog.csdn.net/kxj19980524/article/details/89281292

其实combiner代码和reduce代码一样

package com.buba.mapreduce.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> {


    //输入<a,1> <a,1> <a,1> 输出<a,3>
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        //计算累加和
        int count = 0;

        for(IntWritable value:values){
            count += value.get();
        }

        //写出
        context.write(key,new IntWritable(count));
    }
}

然后在driver里指定一下就行了

通过日志信息也可以看出起作用了,不写Combiner的话它这里就是0

猜你喜欢

转载自blog.csdn.net/kxj19980524/article/details/89313987