阅读目录
-
MapReduce是什么?
Map Reduce是Google公司开源的一项重要技术,它是一个编程模型,用以进行大数据量的计算。MapReduce采用“分而治之”思想,把对大规模数据集的操作,分发给一个主节点管理下的各个子节点共同完成,然后整合各个子节点的中间结果,得到最终的计算结果。 -
MapReduce实现WordCount的实现思路:
将hdfs上的文本作为输入,MapReduce通过InputFormat会将文本进行切片处理(按行读入),每出现一个单词就标记一个数字1,经过在map函数处理,输出中间结果<单词,1>的形式,并在reduce函数中完成对每个单词的词频统计。
软件:IntelliJ IDEA
一、创建项目 :example-hdfs
二、项目目录
三、WordCountMapper.class
继承Mapper类实现自己的Mapper类,并重写map()方法
package cn.it.cast.hadoop.mr;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class WordCountMapper extends Mapper<LongWritable,Text,Text,IntWritable> {
@Override
//每传入一个<k,v>,该方法就被调用一次
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
//拿到传入的传入进来的一行内容,把数据类型转化为String
String line = value.toString();
//将这一行内容按照分隔符进行一行内容的切割,切割成一个单词数组
String[] words = line.split(" ");
//遍历数组,每出现一个单词,就标记一个数字1,<单词,1>
for(String word:words){
context.write(new Text(word),new IntWritable(1));
}//使用mr程序的上下文context,把Map阶段处理的数据发送出去,作为reduce节点的输入数据
}
}
四、WordCountReducer.class
继承Reducer类,实现自己的Reduce类,并重写reduce()方法
package cn.it.cast.hadoop.mr;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class WordCountReducer extends Reducer<Text, IntWritable, Text,IntWritable>