现在,我们不是计算一个最大值了(想了解如何计算最大值,可以参考Hadoop MapReduce编程:计算最大值),而是计算一个最大值和一个最小值。实际上,实现Mapper和Reducer也是非常简单的,但是我们要输出结果,需要能够区分出最大值和最小值,并同时输出结果,这就需要自定义自己的输出类型,以及需要定义输出格式。
测试数据
数据格式,如下所示:
01 |
SG 253654006139495 253654006164392 619850464 |
02 |
KG 253654006225166 253654006252433 743485698 |
03 |
UZ 253654006248058 253654006271941 570409379 |
04 |
TT 253654006282019 253654006286839 23236775 |
05 |
BE 253654006276984 253654006301435 597874033 |
06 |
BO 253654006293624 253654006315946 498265375 |
07 |
SR 253654006308428 253654006330442 484613339 |
08 |
SV 253654006320312 253654006345405 629640166 |
09 |
LV 253654006330384 253654006359891 870680704 |
10 |
FJ 253654006351709 253654006374468 517965666 |
上面文本数据一行一行存储,一行包含4部分,分别表示:
- 国家代码
- 起始时间
- 截止时间
- 随机成本/权重估值
各个字段之间以空格号分隔。我们要计算的结果是,求各个国家(以国家代码标识)的成本估值的极值(最大值和最小值)。
编程实现
首先,我们应该考虑需要实现哪些内容,才能满足我们的编程需要。
Mapper中输入数据类型分别为:K1=>LongWritable,V1=>Text,K1表示文本文件中行偏移量,V1表示一行的文本内容;输出数据类型分别为:K2=>Text,V2=>LongWritable,K2表示我们解析出来的国家代码,是字符串类型,V2表示成本估算值,是一个数字类型。
而Reducer的输入即为<K2, list>,输出我们设计为,K3=>Text,是国家代码,V3是我们自己定义的类型,这个类中应该包含最大值和最小值。
另外,因为Reducer运行阶段我们得到最终的输出,而且是输出到HDFS中。我们设计了输出对象的类型,但是还需要设计一个用来描述输出数据的格式,其中包含了应该如何将最终的数据写入到HDFS中。
有关Mapper的实现,可以参考Hadoop MapReduce编程:计算最大值,这里,为了计算极值,需要实现如下内容:
- Reducer输出类型
- Reducer输出规格说明的定义
- Mapper实现
- Reducer实现
- 配置Job
下面,我们详细说明如何去实现:
Reducer的输出Value类型应该定义两个字段:最大值和最小值,这样才能在最终的输出中同时看到同一个国家代码对应的极值数据。我们定义了Extremum类来代表极值,实现代码如下所示:
01 |
package org.shirdrn.kodz.inaction.hadoop.extremum; |
03 |
import java.io.DataInput; |
04 |
import java.io.DataOutput; |
05 |
import java.io.IOException; |
07 |
import org.apache.hadoop.io.LongWritable; |
08 |
import org.apache.hadoop.io.Writable; |
10 |
public class Extremum implements Writable { |
12 |
private LongWritable maxValue; |
13 |
private LongWritable minValue; |
17 |
maxValue = new LongWritable(0); |
18 |
minValue = new LongWritable(0); |
21 |
public Extremum(long min, long max) { |
23 |
this.minValue = new LongWritable(min); |
24 |
this.maxValue = new LongWritable(max); |
28 |
public void readFields(DataInput in) throws IOException { |
29 |
minValue.readFields(in); |
30 |
maxValue.readFields(in); |
34 |
public void write(DataOutput out) throws IOException { |
39 |
public LongWritable getMaxValue() { |
43 |
public void setMaxValue(LongWritable maxValue) { |
44 |
this.maxValue = maxValue; |
47 |
public LongWritable getMinValue() { |
51 |
public void setMinValue(LongWritable minValue) { |
52 |
this.minValue = minValue; |
56 |
public String toString() { |
57 |
StringBuilder builder = new StringBuilder(); |
58 |
builder.append(minValue.get()).append("\t").append(maxValue.get()); |
59 |
return builder.toString(); |
我们自己定义的类型必须实现Hadoop定义的Writable接口,这样才能够实用Hadoop的序列化机制,最终将数据写入到HDFS。该接口定义了两个方法,分别对应于序列化和反序列化操作。
这个自定义类型中,封装了最大值和最小值两个字段。
Reducer输出,实际上就是我们写个这个Job的输出。我们定义了ExtremumOutputFormat类,该类描述Reducer输出规格的,你可以参考Hadoop自带的TextOutputFormat类,重写自带的getRecordWriter方法,来实现我们自己输出结果的操作。ExtremumOutputFormat类实现代码如下所示:
01 |
package org.shirdrn.kodz.inaction.hadoop.extremum; |
03 |
import java.io.DataOutputStream; |
04 |
import java.io.IOException; |
05 |
import java.io.UnsupportedEncodingException; |
07 |
import org.apache.hadoop.conf.Configuration; |
08 |
import org.apache.hadoop.fs.FSDataOutputStream; |
09 |
import org.apache.hadoop.fs.FileSystem; |
10 |
import org.apache.hadoop.fs.Path; |
11 |
import org.apache.hadoop.io.Text; |
12 |
import org.apache.hadoop.io.compress.CompressionCodec; |
13 |
import org.apache.hadoop.io.compress.GzipCodec; |
14 |
import org.apache.hadoop.mapreduce.RecordWriter; |
15 |
import org.apache.hadoop.mapreduce.TaskAttemptContext; |
16 |
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; |
17 |
import org.apache.hadoop.util.ReflectionUtils; |
19 |
public class ExtremumOutputFormat extends TextOutputFormat<Text, Extremum> { |
22 |
public RecordWriter<Text, Extremum> getRecordWriter(TaskAttemptContext job) |
23 |
throws IOException, InterruptedException { |
25 |
Configuration conf = job.getConfiguration(); |
26 |
boolean isCompressed = getCompressOutput(job); |
27 |
String fieldSeparator= conf.get("mapred.textoutputformat.separator", "\t"); |
28 |
CompressionCodec codec = null; |
29 |
String extension = ""; |
31 |
Class<? extends CompressionCodec> codecClass = getOutputCompressorClass(job, GzipCodec.class); |
32 |
codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); |
33 |
extension = codec.getDefaultExtension(); |
35 |
Path file = getDefaultWorkFile(job, extension); |
36 |
FileSystem fs = file.getFileSystem(conf); |
37 |
FSDataOutputStream fileOut = fs.create(file, false); |
39 |
return new ExtremumRecordWriter(fileOut, fieldSeparator); |
41 |
DataOutputStream out = newDataOutputStream(codec.createOutputStream(fileOut)); |
42 |
return new ExtremumRecordWriter(out, fieldSeparator); |
46 |
public static class ExtremumRecordWriter extends RecordWriter<Text, Extremum> { |
48 |
private static final String CHARSET = "UTF-8"; |
49 |
protected DataOutputStream out; |
50 |
private final byte[] fieldSeparator; |
51 |
private static final byte[] NEWLINE; |
54 |
NEWLINE = "\n".getBytes(CHARSET); |
55 |
} catch (UnsupportedEncodingException uee) { |
56 |
throw new IllegalArgumentException("can't find " + CHARSET + " encoding."); |
60 |
public ExtremumRecordWriter(DataOutputStream out) { |
64 |
public ExtremumRecordWriter(DataOutputStream out, String fieldSeparator) { |
68 |
this.fieldSeparator = fieldSeparator.getBytes(CHARSET); |
69 |
} catch (UnsupportedEncodingException e) { |
70 |
throw new IllegalArgumentException("can't find " + CHARSET + " encoding."); |
75 |
public synchronized void close(TaskAttemptContext context) throwsIOException, |
76 |
InterruptedException { |
81 |
public synchronized void write(Text key, Extremum value) throws IOException, |
82 |
InterruptedException { |
84 |
out.write(key.getBytes(), 0, key.getLength()); |
85 |
out.write(fieldSeparator); |
88 |
out.write(value.getMinValue().toString().getBytes()); |
89 |
out.write(fieldSeparator); |
90 |
out.write(value.getMaxValue().toString().getBytes()); |
我们实现的ExtremumOutputFormat类,在getRecordWriter方法中返回一个ExtremumRecordWriter实例,这个实例就是用来执行写入输出结果的,上面输出结果的格式就是“国家代码最小值最大值”,各个字段时间使用TAB分隔,一共三列。
Mapper实现就是解析一行文本数据,抽取出国家代码和成本估值,直接列出我们实现的ExtremunGlobalCostMapper累代码,如下所示:
01 |
package org.shirdrn.kodz.inaction.hadoop.extremum; |
03 |
import java.io.IOException; |
05 |
import org.apache.hadoop.io.LongWritable; |
06 |
import org.apache.hadoop.io.Text; |
07 |
import org.apache.hadoop.mapreduce.Mapper; |
09 |
public class ExtremunGlobalCostMapper extends |
10 |
Mapper<LongWritable, Text, Text, LongWritable> { |
12 |
private LongWritable costValue = new LongWritable(1); |
13 |
private Text code = new Text(); |
16 |
protected void map(LongWritable key, Text value, Context context) |
17 |
throws IOException, InterruptedException { |
19 |
String line = value.toString(); |
20 |
String[] array = line.split("\\s"); |
21 |
if (array.length == 4) { |
22 |
String countryCode = array[0]; |
23 |
String strCost = array[3]; |
26 |
cost = Long.parseLong(strCost); |
27 |
} catch (NumberFormatException e) { |
31 |
code.set(countryCode); |
33 |
context.write(code, costValue); |
Reducer实现也不是很复杂,需要注意的是,计算出最小值和最大值之后,将它们包装到非Hadoop定义的类型的实例中,这里是Extremum类。我们实现的ExtremumGlobalCostReducer类,代码如下所示:
01 |
package org.shirdrn.kodz.inaction.hadoop.extremum; |
03 |
import java.io.IOException; |
04 |
import java.util.Iterator; |
06 |
import org.apache.hadoop.io.LongWritable; |
07 |
import org.apache.hadoop.io.Text; |
08 |
import org.apache.hadoop.mapreduce.Reducer; |
10 |
public class ExtremumGlobalCostReducer extends |
11 |
Reducer<Text, LongWritable, Text, Extremum> { |
14 |
protected void reduce(Text key, Iterable<LongWritable> values, |
15 |
Context context) throws IOException, InterruptedException { |
17 |
long min = Long.MAX_VALUE; |
18 |
Iterator<LongWritable> iter = values.iterator(); |
19 |
while (iter.hasNext()) { |
20 |
LongWritable current = iter.next(); |
21 |
if (current.get() > max) { |
24 |
if (current.get() < min) { |
28 |
Extremum extremum = new Extremum(min, max); |
29 |
context.write(key, extremum); |
配置Job,需要按照我们定义的输出值类型,以及输出规格说明来进行配置,我们实现的MapReduce程序的配置逻辑,实现类为ExtremumCostDriver,代码如下所示:
01 |
package org.shirdrn.kodz.inaction.hadoop.extremum; |
03 |
import java.io.IOException; |
05 |
import org.apache.hadoop.conf.Configuration; |
06 |
import org.apache.hadoop.fs.Path; |
07 |
import org.apache.hadoop.io.LongWritable; |
08 |
import org.apache.hadoop.io.Text; |
09 |
import org.apache.hadoop.mapreduce.Job; |
10 |
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; |
11 |
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; |
12 |
import org.apache.hadoop.util.GenericOptionsParser; |
14 |
public class ExtremumCostDriver { |
16 |
public static void main(String[] args) throws IOException, |
17 |
InterruptedException, ClassNotFoundException { |
19 |
Configuration conf = new Configuration(); |
20 |
String[] otherArgs = new GenericOptionsParser(conf, args) |
22 |
if (otherArgs.length != 2) { |
23 |
System.err.println("Usage: extremumcost <in> <out>"); |
27 |
Job job = new Job(conf, "extremum cost"); |
29 |
job.setJarByClass(ExtremumCostDriver.class); |
30 |
job.setMapperClass(ExtremunGlobalCostMapper.class); |
31 |
job.setReducerClass(ExtremumGlobalCostReducer.class); |
33 |
job.setMapOutputKeyClass(Text.class); |
34 |
job.setMapOutputValueClass(LongWritable.class); |
35 |
job.setOutputKeyClass(Text.class); |
36 |
job.setOutputValueClass(Extremum.class); |
37 |
job.setOutputFormatClass(ExtremumOutputFormat.class); |
39 |
job.setNumReduceTasks(2); |
41 |
FileInputFormat.addInputPath(job, new Path(otherArgs[0])); |
42 |
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); |
44 |
int exitFlag = job.waitForCompletion(true) ? 0 : 1; |
45 |
System.exit(exitFlag); |
这里,一定要正确设置对应阶段的Key和Value输出类型,以及我们定义的输出规格描述类型。另外,我们设置了启动2个Reduce任务,最终会输出2个结果文件。
运行程序
下面看运行程序的过程:
- 编译代码(我直接使用Maven进行),打成jar文件
1 |
shirdrn@SYJ:~/programs/eclipse-jee-juno/workspace/kodz-all/kodz-hadoop/target/classes$ jar -cvf global-extremum-cost.jar -C ./ org |
- 拷贝上面生成的jar文件,到NameNode环境中
1 |
scp shirdrn@172.0.8.212:~/programs/eclipse-jee-juno/workspace/kodz-all/kodz-hadoop/target/classes/global-extremum-cost.jar ./xiaoxiang@ubuntu3:/opt/stone/cloud/hadoop-1.0.3$ bin/hadoop fs -copyFromLocal /opt/stone/cloud/dataset/data_10m /user/xiaoxiang/datasets/cost/ |
1 |
xiaoxiang@ubuntu3:/opt/stone/cloud/hadoop-1.0.3$ bin/hadoop fs -copyFromLocal /opt/stone/cloud/dataset/data_10m /user/xiaoxiang/datasets/cost/ |
1 |
xiaoxiang@ubuntu3:/opt/stone/cloud/hadoop-1.0.3$ bin/hadoop jar global-extremum-cost.jar org.shirdrn.kodz.inaction.hadoop.extremum.ExtremumCostDriver /user/xiaoxiang/datasets/cost /user/xiaoxiang/output/extremum/cost |
运行过程控制台输出内容,如下所示:
01 |
13/03/22 21:38:46 INFO input.FileInputFormat: Total input paths to process : 1 |
02 |
13/03/22 21:38:46 INFO util.NativeCodeLoader: Loaded the native-hadoop library |
03 |
13/03/22 21:38:46 WARN snappy.LoadSnappy: Snappy native library not loaded |
04 |
13/03/22 21:38:46 INFO mapred.JobClient: Running job: job_201303111631_0012 |
05 |
13/03/22 21:38:47 INFO mapred.JobClient: map 0% reduce 0% |
06 |
13/03/22 21:39:03 INFO mapred.JobClient: map 21% reduce 0% |
07 |
13/03/22 21:39:06 INFO mapred.JobClient: map 28% reduce 0% |
08 |
13/03/22 21:39:18 INFO mapred.JobClient: map 48% reduce 4% |
09 |
13/03/22 21:39:21 INFO mapred.JobClient: map 57% reduce 9% |
10 |
13/03/22 21:39:34 INFO mapred.JobClient: map 78% reduce 14% |
11 |
13/03/22 21:39:37 INFO mapred.JobClient: map 85% reduce 19% |
12 |
13/03/22 21:39:49 INFO mapred.JobClient: map 100% reduce 23% |
13 |
13/03/22 21:39:52 INFO mapred.JobClient: map 100% reduce 28% |
14 |
13/03/22 21:40:01 INFO mapred.JobClient: map 100% reduce 30% |
15 |
13/03/22 21:40:04 INFO mapred.JobClient: map 100% reduce 33% |
16 |
13/03/22 21:40:07 INFO mapred.JobClient: map 100% reduce 66% |
17 |
13/03/22 21:40:10 INFO mapred.JobClient: map 100% reduce 100% |
18 |
13/03/22 21:40:15 INFO mapred.JobClient: Job complete: job_201303111631_0012 |
19 |
13/03/22 21:40:15 INFO mapred.JobClient: Counters: 29 |
20 |
13/03/22 21:40:15 INFO mapred.JobClient: Job Counters |
21 |
13/03/22 21:40:15 INFO mapred.JobClient: Launched reduce tasks=2 |
22 |
13/03/22 21:40:15 INFO mapred.JobClient: SLOTS_MILLIS_MAPS=98141 |
23 |
13/03/22 21:40:15 INFO mapred.JobClient: Total time spent by all reduces waiting after reserving slots (ms)=0 |
24 |
13/03/22 21:40:15 INFO mapred.JobClient: Total time spent by all maps waiting after reserving slots (ms)=0 |
25 |
13/03/22 21:40:15 INFO mapred.JobClient: Launched map tasks=7 |
26 |
13/03/22 21:40:15 INFO mapred.JobClient: Data-local map tasks=7 |
27 |
13/03/22 21:40:15 INFO mapred.JobClient: SLOTS_MILLIS_REDUCES=111222 |
28 |
13/03/22 21:40:15 INFO mapred.JobClient: File Output Format Counters |
29 |
13/03/22 21:40:15 INFO mapred.JobClient: Bytes Written=4339 |
30 |
13/03/22 21:40:15 INFO mapred.JobClient: FileSystemCounters |
31 |
13/03/22 21:40:15 INFO mapred.JobClient: FILE_BYTES_READ=260079964 |
32 |
13/03/22 21:40:15 INFO mapred.JobClient: HDFS_BYTES_READ=448913653 |
33 |
13/03/22 21:40:15 INFO mapred.JobClient: FILE_BYTES_WRITTEN=390199096 |
34 |
13/03/22 21:40:15 INFO mapred.JobClient: HDFS_BYTES_WRITTEN=4339 |
35 |
13/03/22 21:40:15 INFO mapred.JobClient: File Input Format Counters |
36 |
13/03/22 21:40:15 INFO mapred.JobClient: Bytes Read=448912799 |
37 |
13/03/22 21:40:15 INFO mapred.JobClient: Map-Reduce Framework |
38 |
13/03/22 21:40:15 INFO mapred.JobClient: Map output materialized bytes=130000084 |
39 |
13/03/22 21:40:15 INFO mapred.JobClient: Map input records=10000000 |
40 |
13/03/22 21:40:15 INFO mapred.JobClient: Reduce shuffle bytes=116610358 |
41 |
13/03/22 21:40:15 INFO mapred.JobClient: Spilled Records=30000000 |
42 |
13/03/22 21:40:15 INFO mapred.JobClient: Map output bytes=110000000 |
43 |
13/03/22 21:40:15 INFO mapred.JobClient: CPU time spent (ms)=121520 |
44 |
13/03/22 21:40:15 INFO mapred.JobClient: Total committed heap usage (bytes)=1763442688 |
45 |
13/03/22 21:40:15 INFO mapred.JobClient: Combine input records=0 |
46 |
13/03/22 21:40:15 INFO mapred.JobClient: SPLIT_RAW_BYTES=854 |
47 |
13/03/22 21:40:15 INFO mapred.JobClient: Reduce input records=10000000 |
48 |
13/03/22 21:40:15 INFO mapred.JobClient: Reduce input groups=233 |
49 |
13/03/22 21:40:15 INFO mapred.JobClient: Combine output records=0 |
50 |
13/03/22 21:40:15 INFO mapred.JobClient: Physical memory (bytes) snapshot=1973850112 |
51 |
13/03/22 21:40:15 INFO mapred.JobClient: Reduce output records=233 |
52 |
13/03/22 21:40:15 INFO mapred.JobClient: Virtual memory (bytes) snapshot=4880068608 |
53 |
13/03/22 21:40:15 INFO mapred.JobClient: Map output records=10000000 |
001 |
xiaoxiang@ubuntu3:/opt/stone/cloud/hadoop-1.0.3$ bin/hadoop fs -cat/user/xiaoxiang/output/extremum/cost/part-r-00000 |
003 |
xiaoxiang@ubuntu3:/opt/stone/cloud/hadoop-1.0.3$ bin/hadoop fs -cat/user/xiaoxiang/output/extremum/cost/part-r-00001 |
005 |
xiaoxiang@ubuntu3:/opt/stone/cloud/hadoop-1.0.3$ bin/hadoop fs -cat/user/xiaoxiang/output/extremum/cost/part-r-00000 |
127 |
xiaoxiang@ubuntu3:/opt/stone/cloud/hadoop-1.0.3$ bin/hadoop fs -cat/user/xiaoxiang/output/extremum/cost/part-r-00001 |
可见,结果符合预期。