shuffle机制中的合并(Combiner)并非咱们以前将的文件合并,他是一种依附于业务性质的调优手段。这里回顾一下咱们以前的参考图java
留意图中第11步的合并过程,这样作以后能够合并一些同key的k-v,节约传输的带宽。apache
Combiner的意义就是对每个maptask的输出进行局部汇总,以减少网络传输量。网络
一、添加自定义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行。日志
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
结果显然是不正确的。