2.1 map阶段
自定义一个类,继承于基类Mapper,该基类是一个泛型,有4个形参类型:用来指定map函数的输入键、输入值,输出键、输 出值,如下 public class Mapper<KEYIN, VALUEIN, KEYOUT, VALUEOUT>,源码位于/usr/local/hadoop-1.0.2/src/mapred/org/apache/hadoop/mapreduce/Mapper.java,但老版本的Mapper是一个接口public interface Mapper<K1, V1, K2, V2> extends JobConfigurable, Closeable ,老版本源码位于/usr/local/hadoop-1.0.2/src/mapred/org/apache/hadoop/mapred/Mapper.java。
根据实际需要,重写map函数,函数类型由Mapper指定。Called once for each key/value pair in the input split. Most applications should override map().每一对<key,value>调用一次map函数。
wordcount程序中,map方法中的value值存储的是文本文件中的一行,key值为该行的首字符相对于文本文件首字符的偏移量,在本程序中,key值未使用。StringTokenizer类是将每一行拆分为一个个的单词。
2.2 reduce阶段
自定义一个类,继承于基类Reducer,该基类是一个泛型,有4个形参类型:用来指定reduce函数的输入键、输入值,输出键、输出值public class Reducer<KEYIN,VALUEIN,KEYOUT,VALUEOUT>,其中reduce的输入类型必须与map的输出类型一致。
根据实际需要,重写reduce方法,方法的类型由Reducer指定,called once for each key. Most applications will define their reduce class by overriding this method。每一个key调用一次reduce方法。
2.3 主函数(作业的配置方法)
注意:新版本中使用/usr/local/hadoop-1.0.2/src/mapred/org/apache/hadoop/mapreduce 中的Job类来进行作业的配置
Job类主要的方法:
setJarByClass(Class<?> cls),作用:Set the Jar by finding where a given class came from.
setOutputKeyClass(Class<?> theClass),作用:Set the key class for the job output data.
setOutputValueClass(Class<?> theClass) ,作用:Set the value class for job outputs.
setJobName(String name)
setMapperClass(Class<? extends Mapper> cls),作用:Set the{@link Mapper} for the job
setReducerClass(Class<? extends Reducer> cls) ,作用: Set the {@link Reducer} for the job
waitForCompletion(boolean verbose ) ,作用:Submit the job to the cluster and wait for it to finish.