理解 MapReduce 执行过程
- 以统计文件中 单词出现的个数为例
- 一共三个文件
1.以整个文件的角度进行图解 ( 每个方块就是一个文件)
2.根据代码进行图解
放上代码,仅供参考
WCMapper.java
public class WCMapper extends Mapper<LongWritable, Text, Text, LongWritable>{
// 重写 map 方法
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text,
LongWritable>.Context context)throws IOException, InterruptedException {
// value 代表文件中的每一行数据
String line = value.toString();
// 根据空格拆分字符串 {hello lilei}
String[] results = line.split(" ");
// 遍历数组 ,获取每一个结果
for (String str : results) {
context.write(new Text(str), new LongWritable(1));// {hello, 1}{lilei, 1}
}
}
}
WCReduce.java
public class WCReduce extends Reducer<Text, LongWritable, Text, LongWritable> {
// 重写reduce 方法
@Override
protected void reduce(Text key2, Iterable<LongWritable> v2,Reducer<Text, LongWritable,
Text, LongWritable>.Context context) throws IOException, InterruptedException {
// 写出自己的逻辑,统计单词个数
// 定义变量存放累加数据
long count = 0;
// v2 -> <hello, {1,1,1,1}
for (LongWritable lw : v2) {
// 累加操作
count += lw.get();
}
// 输出 k3,v3 -> string, long
context.write(key2, new LongWritable(count));
}
}
WCCount.java
public class WCCount {
public static void main(String[] args) throws Exception {
// 1.获取job
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
// 2.指定job使用的类 指定程序的入口
job.setJarByClass(WordCount.class);
// 3.设置Mapper的属性
job.setMapperClass(WCMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(LongWritable.class);
// 4.设置输入文件
FileInputFormat.setInputPaths(job, new Path("/words"));
// 5.设置reducer的属性
job.setReducerClass(WCReduce.class);
job.setOutputKeyClass(Text.class);
job.setMapOutputValueClass(LongWritable.class);
// 6.设置输出文件夹 查看结果,保存到 hdfs 文件夹中的位置
FileOutputFormat.setOutputPath(job, new Path("/wcoutx1"));
// 7.提交 true 提交的时候打印日志信息
job.waitForCompletion(true);
}
}