千家信息网

学习日志---初次接触mapreduce

发表于:2025-02-03 作者:千家信息网编辑
千家信息网最后更新 2025年02月03日,wordcount程序package org.robby.mr;import java.io.IOException;import java.util.StringTokenizer;import o
千家信息网最后更新 2025年02月03日学习日志---初次接触mapreduce

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是每一行的内容,使用的是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 {    private IntWritable result = new IntWritable();    //传入一个单词和其对于的次数迭代器    public void reduce(Text key, Iterable values,                        Context context                       ) throws IOException, InterruptedException {      int sum = 0;      for (IntWritableval : 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  ");      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的目录。

0