Combiner是MR程序中Mapper和Reducer之外的一种组件
Combiner组件的父类就是Reducer
Combiner和Reducer的区别在于运行位置
Combiner是在每一个MapTask所在的节点运行
Reducer是接受全局所以Mapper的输出结果
Combiner 的意义就是对每一个的输出结果进行汇总
Combiner 能够应用的前提是不会影响业务逻辑
如何自定义一个Combiner
- public class WordCountCombiner extends Reducer
{ -
- private IntWritable outV = new IntWritable();
-
- @Override
- protected void reduce(Text key, Iterable
values, Context context) throws IOException, InterruptedException { -
- int sum = 0;
- for (IntWritable value : values) {
- sum += value.get();
- }
-
- outV.set(sum);
-
- context.write(key,outV);
- }
- }
在Job中设置驱动
job.setCombinerClass(WordCountCombiner.class);
Combiner合并案例
需求
统计过程中对每一个MapTask的输出进行局部汇总,以减小网络传输量即采用Combiner功能。
数据输入
hello.txt
期望输出数据
期望:Combine输入数据多,输出时经过合并,输出数据降低。

添加一个
- 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
{ -
- private IntWritable outV = new IntWritable();
-
- @Override
- protected void reduce(Text key, Iterable
values, Context context) throws IOException, InterruptedException { -
- int sum = 0;
- for (IntWritable value : values) {
- sum += value.get();
- }
-
- //封装outKV
- outV.set(sum);
-
- //写出outKV
- context.write(key,outV);
- }
在Driver类中指定Combiner
- // 指定需要使用combiner,以及用哪个类作为combiner的逻辑
- job.setCombinerClass(WordCountCombiner.class);
方案二:
因为Combiner 是reducer的子类
将WordCountReducer作为Combiner
- // 指定需要使用Combiner,以及用哪个类作为Combiner的逻辑
- job.setCombinerClass(WordCountReducer.class);