之前花了点时间玩spark, 现在开始学一下hadoop
前面花了几天时间搭建Hadoop环境和开发环境, 具体就不多说了, 今天开始了第一个Map/Reduce程序, 经典的wordcount。
使用的Hadoop版本是2.6.3, 所以我会用最新的API, 大部分都是在org.apache.hadoop.mapreduce这个包下面的。 (mapred是老的api)
我的sample文件是:
hdfs://<IP>:<Port>/words.txt
内容:
1
2
1
a
b
a
v
c
c
c
c
输出路径为:
hdfs://<IP>:<Port>/output
首先创建Mapper类, 由于我没有设置setInputFormatClass, 所以默认会用TextInputFormat.class, 传进来的Key是LongWritable, value是Text
接下来创建Reducer, 接收的Key value类型为Map的输出, 所以就是 Text, IntWritable。 在Map到reduce之间会shuffle, 过程会把key相同的value放到同一个迭代器里面, 每个key作为一次reduce的输入, 然后在reduce里面对value进行计算:
之后就是要在main里面提交Job了:
然后右键"Run On Hadoop" 就能成功运行了
接下来会写篇文章关于combiner, Map输出的自定义sort, grouping, partition,自定义类型和采集器的示例
前面花了几天时间搭建Hadoop环境和开发环境, 具体就不多说了, 今天开始了第一个Map/Reduce程序, 经典的wordcount。
使用的Hadoop版本是2.6.3, 所以我会用最新的API, 大部分都是在org.apache.hadoop.mapreduce这个包下面的。 (mapred是老的api)
我的sample文件是:
hdfs://<IP>:<Port>/words.txt
内容:
1
2
1
a
b
a
v
c
c
c
c
输出路径为:
hdfs://<IP>:<Port>/output
首先创建Mapper类, 由于我没有设置setInputFormatClass, 所以默认会用TextInputFormat.class, 传进来的Key是LongWritable, value是Text
//传进来的Key是LongWritable, value是Text, 输出为Key Text, 一个Int型的计数
public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
private static IntWritable one = new IntWritable(1);
private Text word = new Text();
@Override
public void map(LongWritable key, Text value, Context context) throws IOException,
InterruptedException {
//获取一行value, 然后分词
String line = value.toString();
StringTokenizer token = new StringTokenizer(line);
while (token.hasMoreElements()) {
word.set(token.nextToken());
//输出到Reducer
context.write(word, one);
}
};
}
接下来创建Reducer, 接收的Key value类型为Map的输出, 所以就是 Text, IntWritable。 在Map到reduce之间会shuffle, 过程会把key相同的value放到同一个迭代器里面, 每个key作为一次reduce的输入, 然后在reduce里面对value进行计算:
//reduce 输入的Key Value为Map的输出
public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
//相同的key的value放到同一个迭代器里面
protected void reduce(Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
int sum = 0;
//数量相加
for (IntWritable value : values) {
sum += value.get();
}
//输出到reduce的路径
context.write(key, new IntWritable(sum));
};
}
之后就是要在main里面提交Job了:
Configuration conf = new Configuration();
//创建Job
Job job = Job.getInstance(conf);
//输入输出
String[] ioArgs = new String[] { "hdfs://10.32.190.165:9000/words.txt",
"hdfs://10.32.190.165:9000/output" };
String[] otherArgs = new GenericOptionsParser(conf, ioArgs).getRemainingArgs();
//设置Job实际执行的类
job.setJarByClass(WordCount.class);
//输入路径
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
//输出路径
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
//设置map类
job.setMapperClass(Map.class);
//设置reduce类
job.setReducerClass(Reduce.class);
//设置输出类型
job.setOutputKeyClass(Text.class);
//输出类型
job.setOutputValueClass(IntWritable.class);
//提交Job
System.exit(job.waitForCompletion(true) ? 0 : 1);
然后右键"Run On Hadoop" 就能成功运行了
接下来会写篇文章关于combiner, Map输出的自定义sort, grouping, partition,自定义类型和采集器的示例