hadoop mapreduce编程
时间: 2025-01-06 07:45:08 浏览: 9
### Hadoop MapReduce 编程教程
#### 1. 理解MapReduce架构
Hadoop中的MapReduce是一个用于处理大规模数据集的编程模型和任务执行框架。它通过将计算分布在多个节点上来加速大数据量的任务完成速度[^1]。
#### 2. 构建简单的WordCount应用程序
下面展示了一个经典的单词计数例子,这是学习MapReduce的一个很好的起点:
```java
import java.io.IOException;
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.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<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
@Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String[] words = value.toString().split("\\s+");
for (String w : words) {
word.set(w.toLowerCase());
context.write(word, one);
}
}
}
public static class SumReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
private IntWritable result = new IntWritable();
@Override
protected 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(SumReducer.class); // 使用组合器来优化性能
job.setReducerClass(SumReducer.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);
}
}
```
此代码实现了基本的映射(Map)操作——读取文件并分割成单独词语;以及简化(Reduce)过程——统计每个词出现次数。为了提高效率,在这里还加入了`setCombinerClass()`方法设置组合器以减少网络传输开销[^2]。
#### 3. 提交Job至YARN集群
当编写好上述Java类之后,可以将其打包为JAR文件,并利用命令行工具向YARN提交作业:
```bash
yarn jar /path/to/your-jar-file.jar com.yourpackage.WordCount input_path output_path
```
这会把程序部署到整个分布式环境中去运行,其中输入路径指向待分析文本的位置而输出路径则是保存最终结果的地方。值得注意的是,这些位置通常是在HDFS之上。
阅读全文