秦悦明的运维笔记

hadoop-oldapi以及运行mapreduce程序

1. 程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package c3;
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.mapred.*;
import java.io.IOException;
import java.util.Iterator;
/**
* Created by gqdw on 28/12/2016.
*/
public class WordCountOldApi {
public static class MyMapper extends MapReduceBase implements
Mapper<LongWritable, Text, Text, IntWritable>{
public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException{
output.collect(new Text(value.toString()), new IntWritable(1));
}
}
public static class MyReducer extends MapReduceBase implements
Reducer<Text, IntWritable, Text, IntWritable>{
public void reduce(Text key, Iterator<IntWritable> values,
OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException{
int sum = 0;
while(values.hasNext()) {
sum += values.next().get();
}
output.collect(key, new IntWritable(sum));
}
}
public static void main(String[] args) throws Exception {
JobConf conf = new JobConf(WordCountOldApi.class);
conf.setJobName("wordcount");
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(MyMapper.class);
conf.setCombinerClass(MyReducer.class);
conf.setNumReduceTasks(1);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
FileInputFormat.setInputPaths(conf, new Path(args[0]));
FileOutputFormat.setOutputPath(conf, new Path(args[1]));
JobClient.runJob(conf);
}
}

maven里面加上依赖:

1
2
3
4
5
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.7.3</version>
</dependency>

编译完了以后得到一个jar包,prohadoop-1.0-SNAPSHOT.jar

2. 运行

其实很简单:

1
hadoop jar prohadoop-1.0-SNAPSHOT.jar c3.WordCountOldApi [input] [output]

input output是指hdfs上面的路径。
首先将文件上传到hdfs

1
hdfs dfs -put test.txt /test

之后即可运行:

1
hadoop jar prohadoop-1.0-SNAPSHOT.jar c3.WordCountOldApi /test/test.txt /test/output

mapreduce程序将结果输出到了output目录,

1
2
-rw-r--r-- 1 gqdw supergroup 0 2016-12-28 17:00 /test/output/_SUCCESS
-rw-r--r-- 1 gqdw supergroup 27 2016-12-28 17:00 /test/output/part-00000

part-00000里面既是结果

1
2
3
4
java 1
job 1
test 3
word 1