Mapreduce中context的作用

在我们写mapreduce的程序时候总会有这么一段代码,这个代码就是map方法的实现,里面有一个参数 context对象,但是这个context对象究竟是干什么的呢?

1
2
3
4
5
6
7
8
9
10
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);
}
}

CONTEXT和其他类和其他接口的关系:

Context 类是Mapper 类的内部抽象类,它实现了MapContext 接口MapContext 里面可以得到split的信息,这个接口实现了 TaskInputOutputContext 这个接口

taskInputOutputContext 这个接口里面一些记录 getCurrentKey、getCurrentValue、nextKeyValue, getOutputCommitter(这个是一个OutputCommitter的抽象类,这个提供了提交的一些操作方法和属性)的方法,这个接口实现了TaskAttemptContext这个接口;

​TaskAttemptContext 这个接口保存了 task的一些信息,这个接口实现了JobContext和Progressable这个接口;

​JobContext和Progressable这个2个接口,这2个接口保存了job的信息和程序运行过程的进展;

​从上面的源码可以看出来, setup方法来处理context对象,可以为对象增加一些新的成员,或者修改之前成员,从map方法来看,context对象是做为一个参数传给map函数,在Mapper类的实例中是可以拿到Context这个上下文对象的.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void run(Context context) throws IOException, InterruptedException 
{
setup(context);
try
{
while(context.nextKeyValue())
{
map(context.getCurrentKey(),context.getCurrentValue(), context);
}
}
finally
{
cleanup(context);
}

}

context它是mapper的一个内部类,简单的说顶级接口是为了在map或是reduce任务中跟踪task的状态,很自然的MapContext就是记录了map执行的上下文,在mapper类中,这个context可以存储一些job conf的信息,比如job运行时参数等,我们可以在map函数中处理这个信息,这也是hadoop中参数传递中一个很经典的例子,同时context作为了map和reduce执行中各个函数的一个桥梁,这个设计和java web中的session对象、application对象很相似.