一 、Mapper编写
继承Mapper类------>重写map方法------>实现具体业务逻辑------>将新的key,value输出
public class WCMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
@Overrideprotected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
//接收数据V1
String line = value.toString();
//按照空格切分成单词
String[] words = line.split(" ");for (String w : words) {
//出现一次记1
context.write(new Text(w), new LongWritable(1));
}
}
}
一 、Reducer编写
继承Reducer类------>重写reduce方法------>实现具体业务逻辑------>将新的key,value输出
public class WCReducer extends Reducer<Text,LongWritable,Text,LongWritable> {
@Override
protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
//接受数据
// Text k3 = key;
//定义一个计数器
long counter = 0;
//遍历values集合,并求和
for(LongWritable i:values){counter += i.get();
}
//将新的key,value输出
context.write(key,new LongWritable(counter));}
}
三 、主函数编写
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
//构建job类
Job job = Job.getInstance(new Configuration());
//注意main方法所在的类,别忘记设置setJarByClass
job.setJarByClass(WordCount.class);
//设置mapper相关属性
job.setMapperClass(WCMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(LongWritable.class);
//设置源文件
FileInputFormat.setInputPaths(job,new Path("/wordcount"));//设置Rueduce相关属性
job.setReducerClass(WCReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
//设置输出文件
//提交任务
job.waitForCompletion(true);
}
}