hadoop入门学习系列之五Eclipse下搭建Hadoop2.6.5开发环境并写wordcount

1. 新建java project

2. 在pom.xml中引入hadoop

<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.6.5</version>
</dependency>

3. 编写wordcount类

3.1 编写mapper类

public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable>{

private final static IntWritable one = new IntWritable(2);

private Text word = new Text();

public void map(Object key, Text value, Context context) throws IOException, InterruptedException {

StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()){
word.set(itr.nextToken());
context.write(word, one);
}

}
}

3.2 编写Reduce类

public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> {

private IntWritable result = new IntWritable();

public void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {
int sum = 0;

for (IntWritable val : values) {

sum += val.get();

}

result.set(sum);

context.write(key, result);

}

}

3.3 编写main函数

public static void main(String[] args) throws Exception {

Configuration conf = new Configuration();

/*String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();

if (otherArgs.length != 2) {

System.err.println("Usage: wordcount <in> <out>");

System.exit(2);

}*/
System.err.println(args.length);
System.err.println(args[0]);
System.err.println(args[1]);
//System.err.println(args[2]);
Job job = new Job(conf, "word count");

job.setJarByClass(WordCount.class);

job.setMapperClass(TokenizerMapper.class);

job.setCombinerClass(IntSumReducer.class);

job.setReducerClass(IntSumReducer.class);

job.setOutputKeyClass(Text.class);

job.setOutputValueClass(IntWritable.class);

FileInputFormat.addInputPath(job, new Path(args[0]));

FileOutputFormat.setOutputPath(job, new Path(args[1]));

System.exit(job.waitForCompletion(true) ? 0 : 1);

}

3.4 运行程序

将代码打包成jar,然后放到linux执行

bin/hadoop jar share/hadoop/mapreduce/WordCount4.jar com.iluxday.WordCount.WordCount /user/hadoopuser/mapreduce/wordcount/input /user/hadoopuser/mapreduce/wordcount/output3

posted @ 2017-07-11 14:48  love fendi  阅读(975)  评论(0编辑  收藏  举报