mapreduce 项目实例
时间: 2023-11-24 11:52:42 浏览: 145
mapreduce示例
以下是一个简单的MapReduce项目实例,实现了对文本中单词出现次数的统计:
1. 定义自己的三个类:DcMapper,DcReducer,DcDriver
```java
public class DcMapper 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 {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken()); context.write(word, one);
}
}
}
public class DcReducer 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 class DcDriver {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(DcDriver.class);
job.setMapperClass(DcMapper.class);
job.setCombinerClass(DcReducer.class);
job.setReducerClass(DcReducer.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);
}
}
```
2. 编写完代码后,将其打包成JAR文件。
3. 将JAR文件上传到Hadoop集群中,并执行以下命令:
```shell
hadoop jar wordcount.jar com.xijing.mapreduce.DcDriver /input /output
```
其中,/input是输入文件路径,/output是输出文件路径。
阅读全文