wordcount程序
package org.robby.mr; import java.io.IOException; import java.util.StringTokenizer; 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.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.GenericOptionsParser; public class WordCount { public static class Map extends Mapper<Object, Text, Text, IntWritable>{ //object是每一行的行表、text是每一行的内容,使用的是hadoop内置的数据结构 //后面的text是指输出的行,也就是单词,IntWritable是单词的个数 private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(Object key, Text value, Context context ) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { //选出单词放在word里,然后用context输出,对应单词加1 word.set(itr.nextToken()); context.write(word, one); } } } public static class Reduce extends Reducer<Text,IntWritable,Text,IntWritable> { private IntWritable result = new IntWritable(); //传入一个单词和其对于的次数迭代器 public void reduce(Text key, Iterable<IntWritable> values, Context context ) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 2) { System.err.println("Usage: wordcount <in> <out>"); System.exit(2); } Job job = Job.getInstance(conf); job.setJarByClass(WordCount.class); // Set up the input job.setInputFormatClass(TextInputFormat.class); TextInputFormat.addInputPath(job, new Path(args[0])); // Mapper job.setMapperClass(Map.class); // Reducer job.setReducerClass(Reduce.class); // Output job.setOutputFormatClass(TextOutputFormat.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); TextOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }
使用hadoop jar web.jar [类的全名称] [输入目录] [输出目录]
输入和输出目录都是hdfs的目录。
原创文章,作者:3628473679,如若转载,请注明出处:https://blog.ytso.com/193614.html