hadoop之WordCount代码编写

hadoop之WordCount代码编写

WCMapper.java

package hadoop.mr;

import java.io.IOException;

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

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

	//long、String不能在hadoop之间进行数据传输,所以必须使用hadoop提供的序列化方法long=>longWriable、String=>Text
	@Override
	protected void map(LongWritable key, Text value,
			org.apache.hadoop.mapreduce.Mapper.Context context)
			throws IOException, InterruptedException {
		//接收数据v1
		String line = value.toString();
		//切分数据
		String[] words = line.split(" ");
		//循环
		for(String w:words){
			//出现一次,记一个一,输出
			context.write(new Text(w),new LongWritable(1));			
		}
	}
	
	
	
	
}

WCReducer.java

package hadoop.mr;

import java.io.IOException;

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

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

	@Override
	protected void reduce(Text key, Iterable<LongWritable> v2s,Context context)
			throws IOException, InterruptedException {
		
		//接收数据
		//定义一个计算器
		long counter = 0;
		//循环v2s
		for(LongWritable i:v2s){
			counter += i.get();
		}
		//输出
		context.write(key, new LongWritable(counter));
		
	}

}

WordCount.java

package hadoop.mr;

import java.io.IOException;

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;


/**
 * 
 * @author Administrator
 * 1.分析具有的业务逻辑,确定输出输入数据的样式
 * 2.定义一个类,继承org.apache.hadoop.mapreduce.Mapper,重写map方法,实现具体业务逻辑。
 * 3.定义一个类,继承org.apache.hadoop.mapreduce.Reducer,重写reduce方法,实现具体业务逻辑。
 * 4.将自定义的mapper和reducter通过job对象组装起来
 */


public class WordCount {

	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		//构建job对象
		Job job = Job.getInstance(new Configuration());
		
		//注意:main方法所在的类
		job.setJarByClass(WordCount.class);
		
		//设置mapper相关属性
		job.setMapperClass(WCMapper.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(LongWritable.class);
		FileInputFormat.setInputPaths(job, new Path("/words.txt"));
		
		//设置reducer相关属性
		job.setReducerClass(WCReducer.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(LongWritable.class);
		FileOutputFormat.setOutputPath(job, new Path("/wcout510"));
		
		//提交任务
		job.waitForCompletion(true);		
	}

}

导出WordCount的jar包:

export->jar file->next->next->Main class里面选择WordCount->Finish。

执行WordCount的jar包:

hadoop jar wc.jar

下面查看最终结果:

相关文章
相关标签/搜索