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

来源:互联网 发布:安卓手机定位软件 编辑:程序博客网 时间:2024/05/21 22:24

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

Hadoop自带例子WordCount.java

[java] view plaincopy
  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 plaincopy
  1. Job job = new Job(conf, "word count");  
语句实例化一个Job对象,然后就为Job对像指定运行时所需的类
[java] view plaincopy
  1. job.setJarByClass(WordCount.class);  
表示告诉Hadoop集群,作业从哪个类开始运行,
[java] view plaincopy
  1. job.setMapperClass(TokenizerMapper.class);  
表示执行哪个类的map方法,我们这里指定的是方法
[java] view plaincopy
  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 plaincopy
  1. job.setReducerClass(IntSumReducer.class);  
这行语句设置用于进行Reduce的类,告诉Hadoop集群执行哪个reduce函数:
[java] view plaincopy
  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 plaincopy
  1. job.setOutputKeyClass(Text.class);  
  2. job.setOutputValueClass(IntWritable.class);  
表示MapReduce执行结束之后,将结果保存在HDFS中时,保存的数据类型。这里将结果的key以Text类型保存,value以IntWritable类型保存。
[java] view plaincopy
  1. FileInputFormat.addInputPath(job, new Path(otherArgs[0]));  
  2. FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));  
分别表示输入和输出的路径。

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