強-大數據第八講

基於Hadoop的WordCount源碼示例:java

 

1、WordCountMain.javaapache

package demo;app

import java.io.IOException;ide

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;oop

public class WordCountMain {orm

public static void main(String[] args) throws Exception {
//建立一個job = map + reduce
Configuration conf = new Configuration();

//建立一個Job
Job job = Job.getInstance(conf);
//指定任務的入口
job.setJarByClass(WordCountMain.class);

//指定job的mapper
job.setMapperClass(WordCountMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(LongWritable.class);

//指定job的reducer
job.setReducerClass(WordCountReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);

//指定任務的輸入和輸出
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));

//提交任務
job.waitForCompletion(true);
}hadoop

}get

2、WordCountMapper.javainput

package demo;源碼

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class WordCountMapper extends Mapper<LongWritable, Text, Text, LongWritable> {

@Override
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
/*
* key: 輸入的key
* value: 數據 I love Beijing
* context: Map上下文
*/
String data= value.toString();
//分詞
String[] words = data.split(" ");

//輸出每一個單詞
for(String w:words){
context.write(new Text(w), new LongWritable(1));
}
}

}

3、WordCountReducer.java

package demo;

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

public class WordCountReducer extends Reducer<Text, LongWritable, Text, LongWritable>{

@Override
protected void reduce(Text k3, Iterable<LongWritable> v3,Context context) throws IOException, InterruptedException {
//v3: 是一個集合,每一個元素就是v2
long total = 0;
for(LongWritable l:v3){
total = total + l.get();
}

//輸出
context.write(k3, new LongWritable(total));
}

}

相關文章
相關標籤/搜索