}
package com.zyf.mr.wordcount;
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.hadoop.mapreduce.Reducer;
public class WCReducer extends Reducer<Text,LongWritable,Text,LongWritable>{
//框架在map处理完成后,将所有kv对缓存起来,进行分组,然后传递一个组<key,values{}>,调用一次reduce方法
//<hello,{1,1,1,1,1,1,1}>
@Override
protected void reduce(Text key,Iterable<LongWritable> values,Context context) throws IOException,InterruptedException{
long count = 0;
//遍历value的list,进行累加求和
for(LongWritable value:values){
count += value.get();
}
//输出这一个单词的统计结果
context.write(key,new LongWritable(count));
}
}
package com.zyf.mr.wordcount;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
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;
/**
* 用来描述一个特定的作业
* 比如,该作业使用哪个类作为逻辑处理中的map,哪个作为reduce
* 还可以指定该作业要处理的数据所在的路径
* 还可以指定作业输出的结果放到哪个路径
* @author zyf
*
*/
public class WCRunner{
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException{
Configuration conf = new Configuration();
Job wcjob = Job.getInstance(conf);
//设置整个job所用的那些类在哪个jar包
wcjob.setJarByClass(WCRunner.class);
wcjob.setMapperClass(WCMapper.class);
wcjob.setReducerClass(WCReducer.class);
//指定reduce的输出数据kv类型
wcjob.setOutputKeyClass(Text.class);
wcjob.setOutputValueClass(LongWritable.class);
//指定mapper的输出数据kv类型
wcjob.setMapOutputKeyClass(Text.class);
wcjob.setMapOutputValueClass(LongWritable.class);
//指定要处理的输入数据存放路径
FileInputFormat.setInputPaths(wcjob,new Path("hdfs://192.168.1.199:8020/input/"));
//指定处理结果的输入数据存放路径
FileOutputFormat.setOutputPath(wcjob,new Path("hdfs://192.168.1.199:8020/output2/"));
wcjob.waitForCompletion(true);
}
}