MapReduce的API操作
MapReduce的工作流程
参考文章:MapReduce工作流程

词频统计API实现
一、环境准备:参考HDFS的API操作
二、编码实现:
创建3个类:Mapper、Reducer、Driver

- 创建Map阶段的WordCountMapper
WordCountMapper代码;
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;
/**
* KEYIN,map阶段输入的kek类型:LongWritable
* VALUEIN,map阶段输入的value类型:Text
* KEYOUT,map阶段输出的key类型:Text
* VALUEOUT,map阶段输出value类型:IntWritable
*/
public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
//在最外层分配输出key、value对象,这样比写在循环里面更节省空间
Text outK = new Text();
IntWritable outV = new IntWritable(1);
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
super.map(key, value, context);
// 1 获取一行
String line = value.toString();
// 2 切割
String[] words = line.split(" ");
// 3 循环写出
for (String word : words) {
//封装
outK.set(word);
//写出
context.write(outK, outV);
}
}
}
- 创建Reduce阶段的WordCountReducer
WordCountReducer代码:
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> {
private IntWritable outV = new IntWritable();
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
int sum = 0;
//执行结果格式为 abc(1,1)
for (IntWritable value : values) {
sum += value.get();
}
outV.set(sum);
//写出
context.write(key,outV);
}
}
- 编写运行时的Driver类WordCountDriver
WordCountDriver代码:
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;
import java.io.IOException;
public class WordCountDriver {
public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
// 1 获取job
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
// 2 设置jar包路径
job.setJarByClass(WordCountDriver.class);
// 3 关联mapper和reducer
job.setMapperClass(WordCountMapper.class);
job.setReducerClass(WordCountReducer.class);
// 4 设置map输出的kv类型
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
// 5 设置最终输出的kv类型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
// 6 设置输入路径
FileInputFormat.setInputPaths(job, new Path("F:\\hello.txt"));
FileOutputFormat.setOutputPath(job, new Path("F:\\hdfs\\output1"));
// 7 提交job,成功返回0,否则返回1
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
这里的输入文本为

运行结果在指定目录下的part-r-00000


427

被折叠的 条评论
为什么被折叠?



