这篇来说说编写一个MapReduce程序都需要做哪些事情.
大体上要编写三个模块:map类,reduce类,以及驱动.
Map
我们编写的map类需要继承org.apache.hadoop.mapreduce.Mapper.在打开Mapper类之后,会看到几个方法以及一个类:
public class Mapper<KEYIN, VALUEIN, KEYOUT, VALUEOUT> {
public abstract class Context
implements MapContext<KEYIN,VALUEIN,KEYOUT,VALUEOUT> {
}
protected void setup(Context context
) throws IOException, InterruptedException {
// NOTHING
}
@SuppressWarnings("unchecked")
protected void map(KEYIN key, VALUEIN value,
Context context) throws IOException, InterruptedException {
context.write((KEYOUT) key, (VALUEOUT) value);
}
protected void cleanup(Context context
) throws IOException, InterruptedException {
// NOTHING
}
public void run(Context context) throws IOException, InterruptedException {
setup(context);
try {
while (context.nextKeyValue()) {
map(context.getCurrentKey(), context.getCurrentValue(), context);
}
} finally {
cleanup(context);
}
}
}
有一个Context类,这个类在编写reduce类需要继承的org.apache.hadoop.mapreduce.Reducer类中也存在.只不过Mapper中的Context实现的是MapContext类,Reducer中实现的是ReduceContext类.
然后还包含4个方法:setup(),map(),cleanup(),run().我们可以在run()中看到其他三个方法的执行顺序:先执行setup(),在try{}中执行map(),在finally中执行cleanup().都将Context实例作为参数传入.
setup()主要用来执行map()之前的一些准备工作,比如