第六篇:Eclipse上运行第一个Hadoop实例 - WordCount(单词统计程序)

需求

       计算出文件中每个单词的频数。要求输出结果按照单词的字母顺序进行排序。每个单词和其频数占一行,单词和频数之间有间隔。

       比如,输入两个文件,其一内容如下:

       hello world

       hello hadoop

       hello mapreduce

       另一内容如下:

       bye world

       bye hadoop

       bye mapreduce

       对应上面给出的输入样例,其输出样例为:

       bye        3

       hadoop    2

       hello      3

       mapreduce   2

       world     2

方案制定

       对该案例,可设计出如下的MapReduce方案:

1. Map阶段各节点完成由输入数据到单词切分再到单词搜集的工作

2. shuffle阶段完成相同单词的聚集再到分发到各个Reduce节点的工作 (shuffle阶段是MapReduce的默认过程)

3. Reduce阶段负责接收所有单词并计算各自频数

代码示例

  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 //导入各种Hadoop包
 22 import org.apache.hadoop.conf.Configuration;
 23 import org.apache.hadoop.fs.Path;
 24 import org.apache.hadoop.io.IntWritable;
 25 import org.apache.hadoop.io.Text;
 26 import org.apache.hadoop.mapreduce.Job;
 27 import org.apache.hadoop.mapreduce.Mapper;
 28 import org.apache.hadoop.mapreduce.Reducer;
 29 import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
 30 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
 31 import org.apache.hadoop.util.GenericOptionsParser;
 32 
 33 // 主类
 34 public class WordCount {
 35         
 36     // Mapper类
 37     public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable>{
 38         
 39         // new一个值为1的整数对象 
 40         private final static IntWritable one = new IntWritable(1);
 41         // new一个空的Text对象
 42         private Text word = new Text();
 43       
 44         // 实现map函数
 45         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
 46             
 47             // 创建value的字符串迭代器
 48             StringTokenizer itr = new StringTokenizer(value.toString());
 49         
 50             // 对数据进行再次分割并输出map结果。初始格式为<字节偏移量,单词> 目标格式为<单词,频率>
 51             while (itr.hasMoreTokens()) {
 52                     word.set(itr.nextToken());
 53                     context.write(word, one);
 54             }
 55         }
 56     }
 57         
 58     // Reducer类
 59     public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
 60     
 61         // new一个值为空的整数对象
 62         private IntWritable result = new IntWritable();
 63 
 64         // 实现reduce函数
 65         public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
 66                 
 67             int sum = 0;
 68             for (IntWritable val : values) {
 69                 sum += val.get();
 70             }
 71                 
 72             // 得到本次计算的单词的频数
 73             result.set(sum);
 74                         
 75             // 输出reduce结果
 76             context.write(key, result);
 77         }
 78     }
 79 
 80     // 主函数
 81     public static void main(String[] args) throws Exception {
 82     
 83         // 获取配置参数
 84         Configuration conf = new Configuration();
 85         String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
 86                 
 87         // 检查命令语法
 88         if (otherArgs.length != 2) {
 89                 System.err.println("Usage: wordcount <in> <out>");
 90                 System.exit(2);
 91         }
 92                 
 93         // 定义作业对象
 94         Job job = new Job(conf, "word count");
 95         // 注册分布式类
 96         job.setJarByClass(WordCount.class);
 97         // 注册Mapper类
 98         job.setMapperClass(TokenizerMapper.class);
 99         // 注册合并类
100         job.setCombinerClass(IntSumReducer.class);
101         // 注册Reducer类
102         job.setReducerClass(IntSumReducer.class);
103         // 注册输出格式类
104         job.setOutputKeyClass(Text.class);
105         job.setOutputValueClass(IntWritable.class);
106         // 设置输入输出路径
107         FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
108         FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
109                 
110         // 运行程序
111         System.exit(job.waitForCompletion(true) ? 0 : 1);
112     }
113 }

运行方法

1. 打开Eclipse并启动Hdfs(方法请参考前文)

2. 新建一个MapReduce工程:”file" -> "new" -> "project",然后选择 "Map/Reduce Project"

  

3. 设置输入目录及文件

在项目工程包里面新建一个名为input的目录,里面存放需要处理的输入文件。这里选用2个文件名分别为file01和file02的文件进行测试。文件内容同需求示例。

       

4. 将输入文件传输入Hdfs

在终端输入以下命令即可将整个目录传输进Hdfs(input目录下的所有文件将会被送进Hdfs下名为input01的目录里),请根据MapReduce工程包实际路径对如下命令略作修改即可:

1 ./bin/hadoop fs -put ../workspace/Hadoop_t1/input/ input01

5. 在工程包中新建一个WordCount类并将上面的源代码拷贝进去。

6. 调整项目运行参数:右键项目 -> “Run As" -> ”Run Configurations"

       

需要添加的就是"Program arguments"下的那些代码。它们其实是作为命令行参数传递进程序的,第一段是输入文件路径;第二段是输出文件路径。

路径的格式为 "[主机IP地址:hdfs端口] + [输入/输出目录在hdfs中的路径]"。

可以输入以下命令查看输入目录路径:

1 ./bin/hadoop fs -ls

       

7. 点击"Run"运行程序。

8. 执行以下命令查看结果:

1 ./bin/hadoop fs -cat output01/*

       

       这些主机和Hdfs的文件传递,显示也可以使用Eclipse,更方便容易。在此就不提了。

  

小结

1. 多多熟练Hadoop平台下MapReduce项目基本创建流程。

2. WordCount是一个很经典的Hadoop示例,它虽然简单,但具有很大的代表性。

3. 从某个程度上来说也反映了其设计的初衷,对日志文件的分析。

posted @ 2017-05-20 08:55  穆晨  阅读(3834)  评论(0编辑  收藏  举报