Hadoop mapper类的阅读

文章转自:http://www.aboutyun.com/thread-5597-1-1.html

在Hadoop的mapper类中,有4个主要的函数,分别是:setup,clearup,map,run。代码如下:

  1. protected void setup(Context context) throws IOException, InterruptedException {
  2. // NOTHING
  3. }

  4. protected void map(KEYIN key, VALUEIN value, 
  5.                      Context context) throws IOException, InterruptedException {
  6. context.write((KEYOUT) key, (VALUEOUT) value);
  7. }

  8. protected void cleanup(Context context) throws IOException, InterruptedException {
  9. // NOTHING
  10. }

  11. public void run(Context context) throws IOException, InterruptedException {
  12.     setup(context);
  13.     while (context.nextKeyValue()) {
  14.       map(context.getCurrentKey(), context.getCurrentValue(), context);
  15.     }
  16.     cleanup(context);
  17.   }
  18. }
复制代码
由上面的代码,我们可以了解到,当调用到map时,通常会先执行一个setup函数,最后会执行一个cleanup函数。而默认情况下,这两个函数的内容都是nothing。因此,当map方法不符合应用要求时,可以试着通过增加setup和cleanup的内容来满足应用的需求。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mapper 、Reducer 和 Driver Hadoop MapReduce 的三个重要组件。下面是它们的基本代码实现: Mapper : ```java public class MyMapper extends Mapper<LongWritable, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] words = line.split(" "); for (String w : words) { word.set(w); context.write(word, one); } } } ``` Reducer : ```java public class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } context.write(key, new IntWritable(sum)); } } ``` Driver : ```java public class MyDriver { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(MyDriver.class); job.setMapperClass(MyMapper.class); job.setCombinerClass(MyReducer.class); job.setReducerClass(MyReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } ``` 以上代码实现了一个简单的 WordCount 示例,其 MyMapper 和 MyReducer 分别实现了 Mapper 和 Reducer 接口,并重写了 map 和 reduce 方法。MyDriver 则是程序的入口,它配置了 Job 的各种参数,并提交运行任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值