Hadoop--08--WordCount

<span style="font-family:SimSun;font-size:18px;">import java.io.IOException;  
import java.util.*;  
import org.apache.hadoop.fs.Path;  
import org.apache.hadoop.conf.*;  
import org.apache.hadoop.io.*;  
import org.apache.hadoop.mapred.*;  
import org.apache.hadoop.util.*;  

public class WordCount {  </span>
<span style="font-family:SimSun;font-size:18px;">
	<span style="white-space:pre">	</span>public static class WordCountMap extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {  

		private final static IntWritable one = new IntWritable(1);  
		private Text word = new Text();  
  
		public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {  
			 String line = value.toString();  
			 StringTokenizer tokenizer = new StringTokenizer(line);  
			 while (tokenizer.hasMoreTokens()) {  
			   word.set(tokenizer.nextToken());  
			   output.collect(word, one);  
			 }  
			}  
		}  
	
		public static class WordCountReduce 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;  
			 while (values.hasNext()) {  
			   sum += values.next().get();  
			 }  
			 output.collect(key, new IntWritable(sum));  
			}  
		
		}  
		
		public static void main(String[] args) throws Exception {  
			JobConf conf = new JobConf(WordCount.class);  
			conf.setJobName("wordcount");  
			  
			conf.setOutputKeyClass(Text.class);  
			conf.setOutputValueClass(IntWritable.class);  
			  
			conf.setMapperClass(Map.class);  
			conf.setReducerClass(Reduce.class);  
			  
			conf.setInputFormat(TextInputFormat.class);  
			conf.setOutputFormat(TextOutputFormat.class);  
			  
			FileInputFormat.setInputPaths(conf, new Path(args[0]));  
			FileOutputFormat.setOutputPath(conf, new Path(args[1]));  
			  
			JobClient.runJob(conf);  
			}  
	}  </span>
程序分析

1、WordCountMap类继承了org.apache.hadoop.mapreduce.Mapper,4个泛型类型分别是map函数输入key的类型,输入value的类型,输出key的类型,输出value的类型。

2、WordCountReduce类继承了org.apache.hadoop.mapreduce.Reducer,4个泛型类型含义与map类相同。
3、map的输出类型与reduce的输入类型相同,而一般情况下,map的输出类型与reduce的输出类型相同,因此,reduce的输入类型与输出类型相同。

4、hadoop根据以下代码确定输入内容的格式:
job.setInputFormatClass(TextInputFormat.class);
TextInputFormat是hadoop默认的输入方法,它继承自FileInputFormat。在TextInputFormat中,它将数据集切割成小数据集InputSplit,每一个InputSplit由一个mapper处理。此外,InputFormat还提供了一个RecordReader的实现,将一个InputSplit解析成<key,value>的形式,并提供给map函数:
key:这个数据相对于数据分片中的字节偏移量,数据类型是LongWritable。
value:每行数据的内容,类型是Text。
因此,在本例中,map函数的key/value类型是LongWritable与Text。

5、Hadoop根据以下代码确定输出内容的格式:
job.setOutputFormatClass(TextOutputFormat.class);
TextOutputFormat是hadoop默认的输出格式,它会将每条记录一行的形式存入文本文件,如
the 30
happy 23
……

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章