更新时间:2024-02-26 来源:黑马程序员 浏览量:

在Hadoop中,Combiner的作用是在Map阶段输出数据之后,但在数据传输到Reducer之前,对Map输出的数据进行一次局部聚合操作。Combiner可以大大减少Map阶段输出的数据量,从而减轻Reducer的负担,提高作业的整体性能。
Combiner通常用于对具有可结合性和可交换性的操作进行局部合并,比如求和、计数等。它们在Map任务的输出上运行,将相同键的值合并到一起,以减少数据传输。
下面是一个简单的示例,演示如何在Hadoop MapReduce作业中使用Combiner:
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WordCount {
public static class TokenizerMapper
extends Mapper<LongWritable, Text, Text, IntWritable>{
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(LongWritable key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
public static class IntSumReducer
extends Reducer<Text,IntWritable,Text,IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values,
Context context
) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class); // 设置Combiner
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
} 假设我们有一个文本文件,其中包含一系列单词,我们想要计算每个单词出现的次数。
在上面的示例中,我们定义了一个简单的WordCount作业。在main函数中,我们使用job.setCombinerClass(IntSumReducer.class)来指定使用IntSumReducer作为Combiner。
在IntSumReducer类中,reduce函数负责将相同键的值相加,这是一个可结合的操作。通过将IntSumReducer作为Combiner,可以在Map阶段对输出的键值对进行局部合并,减少数据传输量。
AI鸿蒙原生智能正式版课程,培养全端跨平台鸿蒙工程师
2026-03-10AI鸿蒙原生智能正式版课程,培养全端跨平台鸿蒙工程师
2026-03-10毕业16个工作日,平均薪资13180元,就业率100%,广州黑马AI智能应用开发(Java)学科20250529班
2026-03-06毕业32个工作日,平均薪资11147元,就业率95%,广州黑马AI智能应用开发(Java)学科20250326班
2026-03-05黑马程序员2025全国就业数据发布:全学科平均就业率92.07%,AI开发类就业平均薪资达11869.67元。
2026-03-05黑马全国校区齐开班!场面太太太壮观了!
2026-03-03