在Hadoop2.0中MapReduce程序的都需要继承org.apache.hadoop.mapreduce.Mapper 和 org.apache.hadoop.mapreduce.Reducer这两个基础类,来定制自己的mapreduce功能,源码中主要的函数如下
Mapper.java
- public void run(Context context) throws IOException, InterruptedException {
- setup(context); // Called once at the beginning of the task.
- while (context.nextKeyValue()) {
- map(context.getCurrentKey(), context.getCurrentValue(), context);
- }
- cleanup(context); // Called once at the end of the task.
- }
- }
- /**
- * Called once for each key/value pair in the input split. Most applications
- * should override this, but the default is the identity function.
- */
- protected void map(KEYIN key, VALUEIN value,
- Context context) throws IOException, InterruptedException {
- context.write((KEYOUT) key, (VALUEOUT) value);
- }
Reducer.java
- public void run(Context context) throws IOException, InterruptedException {
- setup(context); // Called once at the beginning of the task.
- while (context.nextKey()) {
- reduce(context.getCurrentKey(), context.getValues(), context);
- }
- cleanup(context); // Called once at the end of the task.
- }
- /**
- * This method is called once for each key. Most applications will define
- * their reduce class by overriding this method. The default implementation
- * is an identity function.
- */
- protected void reduce(KEYIN key, Iterable<VALUEIN> values, Context context
- ) throws IOException, InterruptedException {
- for(VALUEIN value: values) {
- context.write((KEYOUT) key, (VALUEOUT) value);
- }
- }
