package cmd;
import org.apache.hadoop.conf.Configured;
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.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* 在命令行使用
* hadoop jar xx.jar INPUT_PATH OUT_PATH
*
* @author Administrator
*
*/
public class WordCountApp
extends Configured implements Tool{
private static String INPUT_PATH = "";
private static String OUT_PATH = "";
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ToolRunner.run(new WordCountApp(), args);
}
@Override
public int
run(String[] args) throws Exception {
INPUT_PATH = args[0];
OUT_PATH = args[1];
Job job = new Job();
job.setJarByClass(WordCountApp.class);
FileInputFormat.setInputPaths(job, INPUT_PATH);
job.setInputFormatClass(TextInputFormat.class);
job.setMapperClass(MyMapper.class);
job.setReducerClass(MyReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
job.setOutputFormatClass(TextOutputFormat.class);
FileOutputFormat.setOutputPath(job, new Path(OUT_PATH));
job.waitForCompletion(true);
return 0;
}
public static class MyMapper extends Mapper<LongWritable, Text, Text, LongWritable>{
protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,Text,LongWritable>.Context context) throws java.io.IOException ,InterruptedException {
final String[] splited = value.toString().split("\t");
for (String word : splited) {
final Text key2 = new Text(word);
final LongWritable value2 = new LongWritable(1L);
context.write(key2, value2);
}
};
}
public static class MyReducer extends Reducer<Text,LongWritable, Text,LongWritable>{
protected void reduce(Text key2, java.lang.Iterable<LongWritable> value2s, org.apache.hadoop.mapreduce.Reducer<Text,LongWritable,Text,LongWritable>.Context context) throws java.io.IOException ,InterruptedException {
Long sum = 0L;
for (LongWritable value2 : value2s) {
sum += value2.get();
}
context.write(key2, new LongWritable(sum));
};
}
}
分享到:
相关推荐
avro-mapred-1.7.7-hadoop2.jar
在MapReduce任务中读取Avro文件,会使用到avro-mapred.jar。 然而目前的avro-mapred.jar是基于较老的版本的,使用时会报错: org.apache.hadoop.mapred.YarnChild: Error running child : java.lang....
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用