`
bo_hai
  • 浏览: 555272 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Hadoop 使用新API写hello word

 
阅读更多

代码如下:

import java.io.IOException;
import java.util.StringTokenizer;

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.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;



public class WordCountNew extends Configured implements Tool{

	public static class WordCountReduceMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
		
		private final static IntWritable one = new IntWritable(1);
		private Text word = new Text();
		
		@Override
		protected void map(LongWritable key, Text value, Context context)throws IOException, InterruptedException {
			// 读取一行数据
			String line = value.toString();
			// 用空格分割成单词
			StringTokenizer st = new StringTokenizer(line);
			// 将单词与数量输出
			while (st.hasMoreTokens()) {
				word.set(st.nextToken());
				context.write(word, one);
			}
		}
	}
	
	
	
		
	public static class WordCountReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
		
		private IntWritable result = new IntWritable();
		
		
		/**
		 * 相同key的数据会一起传送给reduce,因此reduce阶段中的key值是相同,values 可以是多个,其值都是1
		 */
		@Override
		protected void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {
			int sum = 0;
			// 通过循环,得出values的和
			for (IntWritable value : values) {
				sum += value.get();
			}
			result.set(sum);
			context.write(key, result);
		}
	}
	
	@Override
	public int run(String[] args) throws Exception {

		Job job = new Job(getConf());
		job.setJarByClass(WordCountNew.class);
		job.setJobName("mywordcount");
		
		job.setInputFormatClass(TextInputFormat.class);
		job.setOutputFormatClass(TextOutputFormat.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		
		job.setMapperClass(WordCountReduceMapper.class);
		job.setReducerClass(WordCountReduce.class);
		job.setCombinerClass(WordCountReduce.class);
		
		FileInputFormat.setInputPaths(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		
		boolean  success = job.waitForCompletion(true);
		return success ? 0:1;
	}	

	public static void main(String[] args) throws Exception {
		int result = ToolRunner.run(new WordCountNew(), args);
		System.exit(result);
	}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics