第二周hadoop

深入学习 Hadoop 的 MapReduce

  • 学习主题:深入理解 MapReduce 编程模型

  • 学习内容:

    • MapReduce 工作原理:详细学习了 Mapper 和 Reducer 的工作过程,包括数据的输入输出。
    • 编写第一个 MapReduce 程序:
      • 确定了实现 Word Count 功能的目标,统计文本文件中每个单词出现的次数。
  • 具体操作:

    • 编写了 Map 类和 Reduce 类,学习了如何实现自定义的 Mapper 和 Reducer。
    • 配置了作业并提交运行,查看了输出结果。
  • 代码示例:

    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.output.FileOutputFormat;
    
    import java.io.IOException;
    import java.util.StringTokenizer;
    
    public class WordCount {
        public static class TokenizerMapper extends Mapper<Object, Text, 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 tokenizer = new StringTokenizer(value.toString());
                while (tokenizer.hasMoreTokens()) {
                    word.set(tokenizer.nextToken());
                    context.write(word, one);
                }
            }
        }
    
        public static class IntSumReducer 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();
            Job job = Job.getInstance(conf, "word count");
            job.setJarByClass(WordCount.class);
            job.setMapperClass(TokenizerMapper.class);
            job.setCombinerClass(IntSumReducer.class);
            job.setReducerClass(IntSumReducer.class);
            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(IntWritable.class);
            FileInputFormat.addInputPath(job, new Path(args[0]));
            FileOutputFormat.setOutputPath(job, new Path(args[1]));
            System.exit(job.waitForCompletion(true) ? 0 : 1);
        }
    }
  • 学习收获:

    • 深入理解了 MapReduce 的工作流程,对 Mapper 和 Reducer 的职责有了清晰的认识。
    • 成功编写并运行了第一个 MapReduce 程序(Word Count),掌握了数据处理的基本逻辑。
    • 通过调试和测试程序,体会到了大数据处理中的常见问题及解决方案。
posted @ 2024-07-13 20:17  痛苦代码源  阅读(7)  评论(0)    收藏  举报