Word Count Example of Hadoop V1.0 – Mapper的实现

本文继续来看Mapper的实现。

Mapper

01 public static class Map
02         extends Mapper<LongWritable, Text, Text, IntWritable> {
03     private final static IntWritable one = new IntWritable(1);
04     private Text word = new Text();
05 
06     public void map(LongWritable key, Text value, Context context)
07             throws IOException, InterruptedException {
08         String line = value.toString();
09         StringTokenizer tokenizer = new StringTokenizer(line);
10         while (tokenizer.hasMoreTokens()) {
11             word.set(tokenizer.nextToken());
12             context.write(word, one);
13         }
14     }
15 }

我们实现了Driver中指定的Map.class,这个类继承自Mapper<LongWritable, Text, Text, IntWritable>,其中四个类型以此是input的key和value,和Mapper输出的Key和Value。

03     private final static IntWritable one = new IntWritable(1);
04     private Text word = new Text();

这两行是定义mapper的输出,看类型就能看出来,Text是mapper输出的key,IntWritable是mapper输出的value。

06     public void map(LongWritable key, Text value, Context context)

继承Mapper就要实现map函数,LongWritable和Text即mapper的输入,Context是mapper和Hadoop系统交互的工具。它可以存储配置数据,还能输出key-value。

getConfiguration()方法返回一个Configuration,里面包含了Hadoop Job的配置数据。程序员可以在配置数据里加入任意的key-value对(例如:Job.getConfiguration().set(“Key”, “Value”)),当然,也可以把它读出来(Context.getConfiguration().get(“Key”))。这种功能一般会在Mapper的setup()方法里面实现。

map(KeyInType, ValInType, Context)是由Mapper.run()方法调用的。map方法处理数据后,通过Context.write(KeyOutType, ValOutType)方法输出。

在mapper结束后,应用程序可以通过重载Mapper的cleanup()方法来做一些需要的收尾工作。

Mapper的输出对的类型不需要和输入对的类型一致,而且给定一个输入对,可以对应于0个或多个输出对。

Context的另一个作用是report progress,可以像Hadoop Job发送任何应用层的状态信息,或者只是告诉别人自己还活着。

转载于:https://www.cnblogs.com/licheng/archive/2011/11/08/2241725.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值