在一堆给定的文本文件中统计输出每一个单词出现的总次数。
1.分析
mapper阶段:
- 将mapstack 传给我们的文本信息内容先转换成string。
- 根据空格将一行切分成单词。
- 将单词输出为<单词,1>的格式。
reducer阶段
- 汇总各个key的个数
- 输出该key的总数
driver阶段
- 获取配置信息
- 指定本程序的jar所在的本地路径
- 关联mapper和reducer类
- 指定map的输出数据kv类型
- 指定最终输出的数据的kv类型
- 指定job的输入原始位置和输出位置
- 提交
2. 编写代码
- 定义一个mapper类
package com.atguigu.mapreduce.wordcount;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
/**
* KEYIN:输入数据的key 文件的行号
* VALUEIN 每行的输入数据
*
* KEYOUT : 输出数据的key
* VALUEOUT: 输出数据的value类型
* @author Administrator
*
*/
public class WordcountMapper extends Mapper<LongWritable, Text, Text, IntWritable>{
//hello world
//atguigu atguigu
@Override
protected void map(LongWritable key, Text value,Context context)
throws IOException, InterruptedException {
//1.获取这一行数据
String line = value.toString();
//2.获取每一个单词
String[] words = line.split(" ");
//3.输出每一个单词
for (String word : words) {
context.write(new Text(word),new IntWritable(1));
}
}
}
2.定义一个reducer类
package com.atguigu.mapreduce.wordcount;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class WordcountReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
@Override
protected void reduce(Text key, Iterable<IntWritable> values,
Context context) throws IOException, InterruptedException {
// 1.统计所有单词个数
int count = 0;
for (IntWritable value : values) {
count+= value.get();
}
//2.输出所有单词数
context.write(key, new IntWritable(count));
}
}
- 定义一个driver类
package com.atguigu.mapreduce.wordcount;
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.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
//驱动主程序
public class WordcountDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
//1.获取job对象信息
Configuration configuration = new Configuration();
Job job = Job.getInstance(configuration);
//2.设置加载jar位置
job.setJarByClass(WordcountDriver.class);
//3.设置mapper和reducer的class类
job.setMapperClass(WordcountMapper.class);
job.setReducerClass(WordcountReducer.class);
//4.设置输出mapper的数据类型
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
//5.设置最终数据输出的类型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
//6.设置输入数据和输出数据路径
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
//7.submit
boolean result = job.waitForCompletion(true);
System.exit(result?0:1);
}
}
3.运行
- 将上述的类打成jar包,拷贝到hadoop集群中
- 启动hadoop集群
- 执行WordCount程序
打开web端HDFS查看结果
将 part-r-00000下载下来查看,满足需求。