hadoop之WordCount源代码分析
//近期在研究hadoop。第一个想要要開始研究的必然是wordcount程序了。看了《hadoop应用开发实战解说》结合自己的理解,对wordcount的源代码进行分析。
<pre name="code" class="java"> package org.apache.hadoop.mapred; import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner; public class WordCount extends Configured implements Tool { /*
这个类实现mapper接口的map方法,输入的是文本总的每一行。 利用StringTokenizer将字符串拆分成单词。然后将输出结果(word, 1)写入到OutputCollector中去
OutputCollector有hadoop框架提供。负责收集mapper和reducer的输出数据,实现map函数和reduce函数时。仅仅须要将输出的<key,value>对向OutputCollector一丢就可以,其余的事情框架会自己处理。
*/
public static class MapClass extends MapReduceBase
implements Mapper<LongWritable, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
/*类中的LongWritable, Text, IntWritable是hadoop中实现的用于封装Java数据类型的类,这些类都可以被串行化从而便于在分布式系统中进行数据交换。可以将它们等同的视为long,string,int的替代品
*/
public void map(LongWritable key, Text value,
OutputCollector<Text, IntWritable> output,
Reporter reporter) throws IOException {
String line = value.toString();
StringTokenizer itr = new StringTokenizer(line);
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
output.collect(word, one);//输出结果(word,1)
}
}
} /*
此类实现的是Reducer接口中的reduce方法。函数中的參数key.value是由mapper输出的中间结果。values是一个iterator(迭代器)
*/
public static class Reduce extends MapReduceBase
implements Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterator<IntWritable> values,
OutputCollector<Text, IntWritable> output,
Reporter reporter) throws IOException {
int sum = 0;
/*
遍历这个迭代器。就行得到有同样的key的全部的value值。
此处的key是一个单词。而value则是词频
*/
while (values.hasNext()) {
sum += values.next().get();
}
//遍历后得到这个单词出现的总次数。
output.collect(key, new IntWritable(sum));
}
} static int printUsage() {
System.out.println("wordcount [-m <maps>] [-r <reduces>] <input> <output>");//输入输入路径
ToolRunner.printGenericCommandUsage(System.out);
return -1;
} /*
Wordcount 中map/reduce项目的主要驱动程序,调用此方法提交的map / reduce任务。在hadoop中一次计算任务成为一个job。可以通过以一个JobConf对象设置怎样执行这个job。此处定义了输出的key 类型是text,而value的类型是IntWritable
*/
public int run(String[] args) throws Exception {
JobConf conf = new JobConf(getConf(), WordCount.class);
conf.setJobName("wordcount"); // key是text(words)
conf.setOutputKeyClass(Text.class);
// value是IntWritable (ints)
conf.setOutputValueClass(IntWritable.class); conf.setMapperClass(MapClass.class);
conf.setCombinerClass(Reduce.class);
conf.setReducerClass(Reduce.class); List<String> other_args = new ArrayList<String>();
for(int i=0; i < args.length; ++i) {
try {
if ("-m".equals(args[i])) {
conf.setNumMapTasks(Integer.parseInt(args[++i]));
} else if ("-r".equals(args[i])) {
conf.setNumReduceTasks(Integer.parseInt(args[++i]));
} else {
other_args.add(args[i]);
}
} catch (NumberFormatException except) {
System.out.println("ERROR: Integer expected instead of " + args[i]);
return printUsage();
} catch (ArrayIndexOutOfBoundsException except) {
System.out.println("ERROR: Required parameter missing from " +
args[i-1]);
return printUsage();
}
}
// Make sure there are exactly 2 parameters left.
if (other_args.size() != 2) {
System.out.println("ERROR: Wrong number of parameters: " +
other_args.size() + " instead of 2.");
return printUsage();
}
FileInputFormat.setInputPaths(conf, other_args.get(0));
FileOutputFormat.setOutputPath(conf, new Path(other_args.get(1))); JobClient.runJob(conf);
return 0;
} public static void main(String[] args) throws Exception {
/* ToolRunner的run方法開始,run方法有三个參数。 第一个是Configuration类的实例,第二个是wordcount的实例,args则是从控制台接收到的命令行数组
*/
int res = ToolRunner.run(new Configuration(), new WordCount(), args);
System.exit(res);
} }
hadoop之WordCount源代码分析的更多相关文章
- Hadoop源代码分析
http://wenku.baidu.com/link?url=R-QoZXhc918qoO0BX6eXI9_uPU75whF62vFFUBIR-7c5XAYUVxDRX5Rs6QZR9hrBnUdM ...
- Hadoop源代码分析(完整版)
Hadoop源代码分析(一) 关键字: 分布式云计算 Google的核心竞争技术是它的计算平台.Google的大牛们用了下面5篇文章,介绍了它们的计算设施. GoogleCluster:http:// ...
- MapReduce源代码分析之JobSubmitter(一)
JobSubmitter.顾名思义,它是MapReduce中作业提交者,而实际上JobSubmitter除了构造方法外.对外提供的唯一一个非private成员变量或方法就是submitJobInter ...
- 伪分布式环境下命令行正确运行hadoop示例wordcount
首先确保hadoop已经正确安装.配置以及运行. 1. 首先将wordcount源代码从hadoop目录中拷贝出来. [root@cluster2 logs]# cp /usr/local/h ...
- Spark SQL Catalyst源代码分析之TreeNode Library
/** Spark SQL源代码分析系列文章*/ 前几篇文章介绍了Spark SQL的Catalyst的核心执行流程.SqlParser,和Analyzer,本来打算直接写Optimizer的,可是发 ...
- 深入理解Spark 2.1 Core (十一):Shuffle Reduce 端的原理与源代码分析
http://blog.csdn.net/u011239443/article/details/56843264 在<深入理解Spark 2.1 Core (九):迭代计算和Shuffle的原理 ...
- MapReduce源代码分析之LocatedFileStatusFetcher
LocatedFileStatusFetcher是MapReduce中一个针对给定输入路径数组,使用配置的线程数目来获取数据块位置的有用类. 它的主要作用就是利用多线程技术.每一个线程相应一个任务.每 ...
- Spark SQL 源代码分析之Physical Plan 到 RDD的详细实现
/** Spark SQL源代码分析系列文章*/ 接上一篇文章Spark SQL Catalyst源代码分析之Physical Plan.本文将介绍Physical Plan的toRDD的详细实现细节 ...
- Spark MLlib之线性回归源代码分析
1.理论基础 线性回归(Linear Regression)问题属于监督学习(Supervised Learning)范畴,又称分类(Classification)或归纳学习(Inductive Le ...
随机推荐
- sun.misc.BASE64Decoder导入异常及处理思路
Java后台保存base64图片数据 使用byte[] bytes = new BASE64Decoder().decodeBuffer(str);需要引入sun.misc.BASE64Decoder ...
- fastjson用法&Gson
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson&l ...
- [原创]用逻辑嗅探破解接触式IC卡口令
最近两周对接触型IC卡很感兴趣,就动手实践了一下,最终实现的效果是通过破解IC卡口令实现对数据修改,然后就可以随意洗衣服喽~IC卡从数据传递方式上划分为接触型和非接触型两种.接触型的卡片表面有金属贴片 ...
- JS组件系列——显示隐藏密码切换的jQuery插件
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8& ...
- vim使用指北 ---- Multiple Windows in Vim
多窗口打开多个文件 vim -o file1 file2 ... ---- 默认上下分割窗口 vim -0n file1 file2 ... ---- vim默认会上下等分n个窗口 分割窗口 :[v] ...
- css水平竖直居中方式
CSS水平和垂直居中的几种实现方法: 1.单行垂直居中 文字在层中垂直居中vertical-align 属性是做不到的.我们这里有个比较巧妙的方法就是:设置height的高度与line-height的 ...
- There is insufficient memory for the Java Runtime Environment to continue问题解决
在linux系统下长时间进行性能測试,连续几次发生server假死无法连接上的情况,无奈仅仅能重新启动server.在測试路径下发现hs_err_pid17285.log文件,打开文件查看其主要内容例 ...
- [转]SQL Server 性能调优(io)
目录 诊断磁盘io问题 常见的磁盘问题 容量替代了性能 负载隔离配置有问题 分区对齐配置有问题 总结 关于io这一块,前面的东西如磁盘大小,磁盘带宽,随机读取写入,顺序读取写入,raid选择,DA ...
- MySql常用函数数学函数、加密函数等(转—收藏)
MySql函数众多,这里只是列举了一部分常用的函数. 一.数学函数 ABS(x) // 返回x的绝对值 BI ...
- 把.apk传到站点server下载
刚刚解决的一个问题,做好的apk上传到server,通过訪问链接下载apk. 解决方法:设置IIS的MIME类型,让IIS web下载支持包含APK等文件在内的多文件类型 1.打开IIS站点,右键属性 ...