什么是Combiner
- Combiner的父类就是Reducer。
- Combiner和Reducer的区别是运行位置不同。Combiner运行在每个maptask所在节点上,Reducer是接收全局所有Mapper的输出结果。
- Combiner的作用是对每一个maptask的输出结果进行局部汇总,减小网络IO和磁盘IO。
- Combiner的使用前提是不能影响业务逻辑。比如求平均数就不可使用Combiner。
Combiner的使用(以wordcount为例)
1.创建Mapper类。
package com.aura.hadoop.combiner;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
/**
* @author panghu
* @description
* @create 2021-02-15-18:22
*/
public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
private Text word = new Text();
private IntWritable one = new IntWritable(1);
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
word.set(value);
context.write(word, one);
}
}
2.创建Reducer类
package com.aura.hadoop.combiner;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
/**
* @author panghu
* @description
* @create 2021-02-15-18:26
*/
public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private Text word = new Text();
private IntWritable cnt = new IntWritable();
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 1;
for (IntWritable value : values) {
sum += value.get();
}
word.set(key);
cnt.set(sum);
context.write(word, cnt);
}
}
3.创建Driver类。因为Combiner本质上就是一个Reducer,我们可以直接指定Combiner类是我们创建的Reducer类。
package com.aura.hadoop.combiner;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.IOException;
/**
* @author panghu
* @description
* @create 2021-02-15-18:31
*/
public class WordCountDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Job job = Job.getInstance(new Configuration());
job.setJarByClass(WordCountDriver.class);
job.setMapperClass(WordCountMapper.class);
job.setReducerClass(WordCountReducer.class);
// 设置combiner,combiner本质上就是一个reducer
job.setCombinerClass(WordCountReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.setInputPaths(job, new Path("D:\\data\\hadoopdata\\word.txt"));
FileOutputFormat.setOutputPath(job, new Path("D:\\data\\out\\wordcount"));
boolean b = job.waitForCompletion(true);
System.exit(b ? 0 : 1);
}
}