Hadoop入门实践之从WordCount程序说起

2024-04-28 22:38

本文主要是介绍Hadoop入门实践之从WordCount程序说起,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这段时间需要学习Hadoop了,以前一直听说Hadoop,但是从来没有研究过,这几天粗略看完了《Hadoop实战》这本书,对Hadoop编程有了大致的了解。接下来就是多看多写了。以Hadoop自带的例子WordCount程序开始,来记录我的Hadoop学习过程。

Hadoop自带例子WordCount.java

[java]  view plain copy
  1. /** 
  2.  *  Licensed under the Apache License, Version 2.0 (the "License"); 
  3.  *  you may not use this file except in compliance with the License. 
  4.  *  You may obtain a copy of the License at 
  5.  * 
  6.  *      http://www.apache.org/licenses/LICENSE-2.0 
  7.  * 
  8.  *  Unless required by applicable law or agreed to in writing, software 
  9.  *  distributed under the License is distributed on an "AS IS" BASIS, 
  10.  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  11.  *  See the License for the specific language governing permissions and 
  12.  *  limitations under the License. 
  13.  */  
  14.   
  15.   
  16. package org.apache.hadoop.examples;  
  17.   
  18. import java.io.IOException;  
  19. import java.util.StringTokenizer;  
  20.   
  21. import org.apache.hadoop.conf.Configuration;  
  22. import org.apache.hadoop.fs.Path;  
  23. import org.apache.hadoop.io.IntWritable;  
  24. import org.apache.hadoop.io.Text;  
  25. import org.apache.hadoop.mapreduce.Job;  
  26. import org.apache.hadoop.mapreduce.Mapper;  
  27. import org.apache.hadoop.mapreduce.Reducer;  
  28. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;  
  29. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;  
  30. import org.apache.hadoop.util.GenericOptionsParser;  
  31.   
  32. public class WordCount {  
  33.   
  34.   public static class TokenizerMapper   
  35.        extends Mapper<Object, Text, Text, IntWritable>{  
  36.       
  37.     private final static IntWritable one = new IntWritable(1);  
  38.     private Text word = new Text();  
  39.         
  40.     public void map(Object key, Text value, Context context  
  41.                     ) throws IOException, InterruptedException {  
  42.       StringTokenizer itr = new StringTokenizer(value.toString());  
  43.       while (itr.hasMoreTokens()) {  
  44.         word.set(itr.nextToken());  
  45.         context.write(word, one);  
  46.       }  
  47.     }  
  48.   }  
  49.     
  50.   public static class IntSumReducer   
  51.        extends Reducer<Text,IntWritable,Text,IntWritable> {  
  52.     private IntWritable result = new IntWritable();  
  53.   
  54.     public void reduce(Text key, Iterable<IntWritable> values,   
  55.                        Context context  
  56.                        ) throws IOException, InterruptedException {  
  57.       int sum = 0;  
  58.       for (IntWritable val : values) {  
  59.         sum += val.get();  
  60.       }  
  61.       result.set(sum);  
  62.       context.write(key, result);  
  63.     }  
  64.   }  
  65.   
  66.   public static void main(String[] args) throws Exception {  
  67.     Configuration conf = new Configuration();  
  68.     String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();  
  69.     if (otherArgs.length != 2) {  
  70.       System.err.println("Usage: wordcount <in> <out>");  
  71.       System.exit(2);  
  72.     }  
  73.     Job job = new Job(conf, "word count");  
  74.     job.setJarByClass(WordCount.class);  
  75.     job.setMapperClass(TokenizerMapper.class);  
  76.     job.setReducerClass(IntSumReducer.class);  
  77.     job.setOutputKeyClass(Text.class);  
  78.     job.setOutputValueClass(IntWritable.class);  
  79.     FileInputFormat.addInputPath(job, new Path(otherArgs[0]));  
  80.     FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));  
  81.     System.exit(job.waitForCompletion(true) ? 0 : 1);  
  82.   }  
  83. }  
这个程序的功能是对文件中各个单词的数目进行统计。

在Wordount.java中有两个静态内部类TokenizerMapper,IntSumReducer,关于静态内部类,可以参考另一篇文章 Java中的静态内部类。这两个类分别对应与MapReduce中的map和reduce。至于为什么要用静态的内部类,个人理解是这样的:一般一个简单作业(Job)包含了一个map过程和一个reduce过程,Job,Map,Reduce写在一个文件中便于文件的组织。但是,Hadoop内部需要使用反射的方式来实例化客户端的Map和Reduce,所以使用了静态内部类的方式,参考了StackOverflow上的一个帖子: Do Mappers and Reducers in Hadoop have to be static classes?,如果不许要将Job,Map和Reduce组织在一起,完全可以将这三个类写在三个类文件中。

在程序的main函数中首先实例化一个Configuration,用于加载Hadoop的配置信息,然后就解析给程序传递的参数,这里我们传递了两个字符串参数,经过解析之后保存在有两个元素的数组otherArgs中,其中otherArgs[0]为要进行统计的文件的路径,otherArgs[1]为经过MapReduce计算之后的结果所保存的位置。
[java]  view plain copy
  1. Job job = new Job(conf, "word count");  
语句实例化一个Job对象,然后就为Job对像指定运行时所需的类
[java]  view plain copy
  1. job.setJarByClass(WordCount.class);  
表示告诉Hadoop集群,作业从哪个类开始运行,
[java]  view plain copy
  1. job.setMapperClass(TokenizerMapper.class);  
表示执行哪个类的map方法,我们这里指定的是方法
[java]  view plain copy
  1. public void map(Object key, Text value, Context context  
  2.                    ) throws IOException, InterruptedException {  
  3.      StringTokenizer itr = new StringTokenizer(value.toString());  
  4.      while (itr.hasMoreTokens()) {  
  5.        word.set(itr.nextToken());  
  6.        context.write(word, one);  
  7.      }  
  8.    }  
这个方法对要进行map的每行数据,使用StringTokenizer类进行分割,分割出来的值在保存到context中进行,从而在reduce中进行单词数量统计。
[java]  view plain copy
  1. job.setReducerClass(IntSumReducer.class);  
这行语句设置用于进行Reduce的类,告诉Hadoop集群执行哪个reduce函数:
[java]  view plain copy
  1. public void reduce(Text key, Iterable<IntWritable> values,   
  2.                       Context context  
  3.                       ) throws IOException, InterruptedException {  
  4.      int sum = 0;  
  5.      for (IntWritable val : values) {  
  6.        sum += val.get();  
  7.      }  
  8.      result.set(sum);  
  9.      context.write(key, result);  
  10.    }  
在这个函数执行之前,Hadoop已经为我们将各个单词的个数大概的归并在一起了,函数的前两个参数是Text 类型和Iterable类型,参数名分别为key和alues,其中在这里key表示在map方法中分割得到的单词,values表示在map阶段统计的单词的数量(由于reduce阶段接收到多个数据结点发送过来的统计结果,所以对应于一个key,可能有多个value,所以将这些value都保存在一迭代器中,然后对迭代器进行遍历,这个过程以后再讨论。),遍历values迭代器,对每个key的数量进行汇总,然后再记录在context中。
[java]  view plain copy
  1. job.setOutputKeyClass(Text.class);  
  2. job.setOutputValueClass(IntWritable.class);  
表示MapReduce执行结束之后,将结果保存在HDFS中时,保存的数据类型。这里将结果的key以Text类型保存,value以IntWritable类型保存。
[java]  view plain copy
  1. FileInputFormat.addInputPath(job, new Path(otherArgs[0]));  
  2. FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));  
分别表示输入和输出的路径。

这个程序相对于Hadoop的例子,我去掉了
[java]  view plain copy
  1. job.setCombinerClass(IntSumReducer.class);  
这行语句,在Hadoop中,Combiner主要用于提升Hadoop的处理效率,为了集中于理解MapReduce,我去掉了这行代码,待以后讨论提升Hadoop性能时,再学习Combiner。
原文地址: 点击打开链接

这篇关于Hadoop入门实践之从WordCount程序说起的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/944443

相关文章

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

从入门到精通MySQL联合查询

《从入门到精通MySQL联合查询》:本文主要介绍从入门到精通MySQL联合查询,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下... 目录摘要1. 多表联合查询时mysql内部原理2. 内连接3. 外连接4. 自连接5. 子查询6. 合并查询7. 插入查询结果摘要前面我们学习了数据库设计时要满

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

Java中的雪花算法Snowflake解析与实践技巧

《Java中的雪花算法Snowflake解析与实践技巧》本文解析了雪花算法的原理、Java实现及生产实践,涵盖ID结构、位运算技巧、时钟回拨处理、WorkerId分配等关键点,并探讨了百度UidGen... 目录一、雪花算法核心原理1.1 算法起源1.2 ID结构详解1.3 核心特性二、Java实现解析2.

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

MySQL 中 ROW_NUMBER() 函数最佳实践

《MySQL中ROW_NUMBER()函数最佳实践》MySQL中ROW_NUMBER()函数,作为窗口函数为每行分配唯一连续序号,区别于RANK()和DENSE_RANK(),特别适合分页、去重... 目录mysql 中 ROW_NUMBER() 函数详解一、基础语法二、核心特点三、典型应用场景1. 数据分

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

深度解析Spring AOP @Aspect 原理、实战与最佳实践教程

《深度解析SpringAOP@Aspect原理、实战与最佳实践教程》文章系统讲解了SpringAOP核心概念、实现方式及原理,涵盖横切关注点分离、代理机制(JDK/CGLIB)、切入点类型、性能... 目录1. @ASPect 核心概念1.1 AOP 编程范式1.2 @Aspect 关键特性2. 完整代码实