Hadoop MapReduce的Hello World实验目的
时间: 2024-06-13 20:07:35 浏览: 179
Hadoop MapReduce的Hello World实验目的是为了让用户了解Hadoop MapReduce的基本概念和使用方法。通过这个实验,用户可以学习如何编写一个简单的MapReduce程序,并将其部署到Hadoop集群上运行。这个实验可以帮助用户更好地理解Hadoop MapReduce的工作原理和应用场景。
以下是Hadoop MapReduce的Hello World实验步骤:
1. 编写MapReduce程序,包括Mapper和Reducer。
2. 将程序打包成jar文件。
3. 将输入数据上传到Hadoop分布式文件系统(HDFS)中。
4. 运行MapReduce程序。
5. 查看输出结果。
以下是一个简单的Hadoop MapReduce的Hello World实验程序:
```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();
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
String[] words = value.toString().split(" ");
for (String w : words) {
word.set(w);
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);
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);
}
}
```
阅读全文