1.在eclipse中运行,运行前配置
hdfs://192.168.1.104:9000/user/vlab/wcinput/* hdfs://192.168.1.104:9000/user/vlab/wcoutput
可以在改运行文件下,右击鼠标,选择 Run configurations配置
2.WordCount代码
package com.zhangdan.wordcount; import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; 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; public class WordCount { public static class WordCountMap extends Mapper<LongWritable, Text, Text, IntWritable> { private final IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); StringTokenizer token = new StringTokenizer(line); while (token.hasMoreTokens()) { //hasMoreTokens方法:测试此 tokenizer 的字符串中是否还有更多的可用标记。 /** * set方法:Set to contain the contents of a string. * nextToken方法:返回此 string tokenizer 的下一个标记。 */ word.set(token.nextToken()); context.write(word, one);//返回的是单词及次数 } } } public static class WordCountReduce extends Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); //System.out.println(key+" "+val); } context.write(key, new IntWritable(sum)); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); //1.创建Job Job job = new Job(conf); //2.设置Job运行的类 job.setJarByClass(WordCount.class); //3.设置job名称 job.setJobName("wordcount"); job.setOutputValueClass(IntWritable.class); //设置Mapper和Reducer类 job.setMapperClass(WordCountMap.class); //job.setCombinerClass(WordCountReduce.class); 这一步要特别说明下,因为这里没需要combine过程,因此不需要这个过程 job.setReducerClass(WordCountReduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); //设置输入文件目录和输出文件目录 FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); //提交运行作业,等待运行结果 job.waitForCompletion(true); } }
运行备注:首先eclipse中必须有权限对hdfs创建文件的权限才可以直接在eclipse中运行
别人写的hadoop集群搭建过程:http://www.cnblogs.com/yhason/archive/2013/05/30/3108908.html,感觉写的好好
原文:http://www.cnblogs.com/xunyingFree/p/5065773.html