1. Mapper类

首先 Mapper类有四个方法:

(1) protected void setup(Context context)

(2) Protected void map(KEYIN key,VALUEIN value,Context context)

(3) protected void cleanup(Context context)

(4) public void run(Context context)

setup()方法一般用来加载一些初始化的工作,像全局文件\建立数据库的链接等等;cleanup()方法是收尾工作,如关闭文件或者执行map()后的键值分发等;map()函数就不多说了.

默认的Mapper的run()方法的核心代码如下:

public void run(Context context) throws IOException,InterruptedException
{
setup(context);
while(context.nextKeyValue())
map(context.getCurrentKey(),context,context.getCurrentValue(),context);
cleanup(context);
}

从代码中也可以看出先执行setup函数,然后是map处理代码,最后是cleanup的收尾工作.值得注意的是,setup函数和cleanup函数由系统作为回调函数只做一次,并不像map函数那样执行多次.

2.setup函数应用

   经典的wordcount在setup函数中加入黑名单就可以实现对黑名单中单词的过滤,详细代码如下:

public class WordCount {
static private String blacklistFileName= "blacklist.dat"; public static class WordCountMap extends
Mapper<LongWritable, Text, Text, IntWritable> { private final IntWritable one = new IntWritable(1);
private Text word = new Text();
private Set<String> blacklist; protected void setup(Context context) throws IOException,InterruptedException {
blacklist=new TreeSet<String>(); try{
FileReader fileReader=new FileReader(blacklistFileName);
BufferedReader bufferedReader=bew BufferedReader(fileReader);
String str;
while((str=bufferedReader.readLine())!=null){
blacklist.add(str);
}
} catch(IOException e){
e.printStackTrace();
}
} public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer token = new StringTokenizer(line);
while (token.hasMoreTokens()) {
word.set(token.nextToken());
if(blacklist.contains(word.toString())){
continue;
}
context.write(word, one);
}
}
} public static class WordCountReduce 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));
}
} public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = new Job(conf);
job.setJarByClass(WordCount.class);
job.setJobName("wordcount"); job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class); job.setMapperClass(WordCountMap.class);
job.setCombinerClass(WordCountReduce.class);
job.setReducerClass(WordCountReduce.class); job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}

3.cleanup应用

求最值最简单的办法就是对该文件进行一次遍历得出最值,但是现实中数据比量比较大,这种方法不能实现。在传统的MapReduce思想中,将文件的数据经 过map迭代出来送到reduce中,在Reduce中求出最大值。但这个方法显然不够优化,我们可采用“分而治之”的思想,不需要map的所有数据全部 送到reduce中,我们可以在map中先求出最大值,将该map任务的最大值送reduce中,这样就减少了数据的传输量。那么什么时候该把这个数据写 出去呢?我们知道,每一个键值对都会调用一次map(),由于数据量大调用map()的次数也就多了,显然在map()函数中将该数据写出去是不明智的, 所以最好的办法该Mapper任务结束后将该数据写出去。我们又知道,当Mapper/Reducer任务结束后会调用cleanup函数,所以我们可以 在该函数中将该数据写出去。了解了这些我们可以看一下程序的代码:

public class TopKApp {
static final String INPUT_PATH = "hdfs://hadoop:9000/input2";
static final String OUT_PATH = "hdfs://hadoop:9000/out2"; public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
final FileSystem fileSystem = FileSystem.get(new URI(INPUT_PATH), conf);
final Path outPath = new Path(OUT_PATH);
if(fileSystem.exists(outPath)){
fileSystem.delete(outPath, true);
} final Job job = new Job(conf , WordCountApp.class.getSimpleName());
FileInputFormat.setInputPaths(job, INPUT_PATH);
job.setMapperClass(MyMapper.class);
job.setReducerClass(MyReducer.class);
job.setOutputKeyClass(LongWritable.class);
job.setOutputValueClass(NullWritable.class);
FileOutputFormat.setOutputPath(job, outPath);
job.waitForCompletion(true);
}
static class MyMapper extends Mapper<LongWritable, Text, LongWritable, NullWritable>{
long max = Long.MIN_VALUE;
protected void map(LongWritable k1, Text v1, Context context) throws java.io.IOException ,InterruptedException {
final long temp = Long.parseLong(v1.toString());
if(temp>max){
max = temp;
}
} protected void cleanup(org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,LongWritable, NullWritable>.Context context) throws java.io.IOException ,InterruptedException {
context.write(new LongWritable(max), NullWritable.get());
}
} static class MyReducer extends Reducer<LongWritable, NullWritable, LongWritable, NullWritable>{
long max = Long.MIN_VALUE;
protected void reduce(LongWritable k2, java.lang.Iterable<NullWritable> arg1, org.apache.hadoop.mapreduce.Reducer<LongWritable,NullWritable,LongWritable,NullWritable>.Context arg2)
throws java.io.IOException ,InterruptedException {
final long temp = k2.get();
if(temp>max){
max = temp;
}
} protected void cleanup(org.apache.hadoop.mapreduce.Reducer<LongWritable,NullWritable,LongWritable,NullWritable>.Context context) throws java.io.IOException ,InterruptedException {
context.write(new LongWritable(max), NullWritable.get());
}
}
}

hadoop之mapper类妙用的更多相关文章

  1. [Hadoop源码解读](二)MapReduce篇之Mapper类

    前面在讲InputFormat的时候,讲到了Mapper类是如何利用RecordReader来读取InputSplit中的K-V对的. 这一篇里,开始对Mapper.class的子类进行解读. 先回忆 ...

  2. MapReduce之Mapper类,Reducer类中的函数(转载)

    Mapper类4个函数的解析 Mapper有setup(),map(),cleanup()和run()四个方法.其中setup()一般是用来进行一些map()前的准备工作,map()则一般承担主要的处 ...

  3. Mapper类/Reducer类中的setup方法和cleanup方法以及run方法的介绍

    在hadoop的源码中,基类Mapper类和Reducer类中都是只包含四个方法:setup方法,cleanup方法,run方法,map方法.如下所示: 其方法的调用方式是在run方法中,如下所示: ...

  4. Hadoop 2:Mapper和Reduce

    Hadoop 2:Mapper和Reduce Understanding and Practicing Hadoop Mapper and Reduce 1 Mapper过程 Hadoop将输入数据划 ...

  5. Job流程:Mapper类分析

    此文紧接Job流程:决定map个数的因素,Map任务被提交到Yarn后,被ApplicationMaster启动,任务的形式是YarnChild进程,在其中会执行MapTask的run()方法.无论是 ...

  6. 【mybatis】idea中 mybatis的mapper类去找对应的mapper.xml中的方法,使用插件mybatis-plugin

    idea中 mybatis的mapper类去找对应的mapper.xml中的方法,使用插件mybatis-plugin,名字可能叫Free mybatis-plugin 安装上之后,可能需要重启ide ...

  7. 【spring boot】mybatis启动报错:Consider defining a bean of type 'com.newhope.interview.dao.UserMapper' in your configuration. 【Mapper类不能被找到】@Mapper 和@MapperScan注解的区别

    启动报错: 2018-05-16 17:22:58.161 ERROR 4080 --- Disconnected from the target VM, address: '127.0.0.1:50 ...

  8. Hadoop之TaskInputOutputContext类

    在MapReduce过程中,每一个Job都会被分成若干个task,然后再进行处理.那么Hadoop是怎么将Job分成若干个task,并对其进行跟踪处理的呢?今天我们来看一个*Context类——Tas ...

  9. Hadoop_MapReduce中Mapper类和Reduce类

    在权威指南中,有个关于处理温度的MapReduce类,具体如下: 第一部分:Map public class MaxTemperatureMapper extends MapReduceBase im ...

随机推荐

  1. WebGl 画线

    效果: 代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...

  2. java学习无止境,工资价更高

    原 推荐10个Java方向最热门的开源项目(8月) 2018年08月28日 17:54:32 SnailClimb在CSDN 阅读数:849   版权声明:本文为博主原创文章,未经博主允许不得转载. ...

  3. 初识hadoop之分布式文件系统(HDFS)

    Hadoop常用发行版: Apache Hadoop CDH  Cloudera Distributed Hadoop HDP  Hortonworks Data Platfrom 分布式文件系统(H ...

  4. Selenium_python自动化第一个测试案例(代码基本规范)

    发生背景: 最近开始整理Selenium+python自动化测试项目中相关问题,偶然间翻起自己当时学习自动化时候写的脚本,发现我已经快认不出来写的什么鬼流水账了,所以今天特别整理下自动化开发Selen ...

  5. keil5 配置 stm32f103rc 软件仿真

  6. skyline画折现bug代码

    <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>加 ...

  7. spark 例子倒排索引

    spark 例子倒排索引 例子描述: [倒排索引(InvertedIndex)] 这个例子是在一本讲spark书中看到的,但是样例代码写的太java化,没有函数式编程风格,于是问了些高手,教我写了份函 ...

  8. (数据科学学习手札51)用pymysql来操控MySQL数据库

    一.简介 pymysql是Python中专门用来操控MySQL数据库的模块,通过pymysql,可以编写简短的脚本来方便快捷地操控MySQL数据库,本文就将针对pymysql的基本功能进行介绍: 二. ...

  9. FPGA时序逻辑中常见的几类延时与时间(五)

    FPGA逻辑代码重要的是理解其中的时序逻辑,延时与各种时间的记忆也是一件头疼的事,这里把我最近看到的比较简单的几类总结起来,共同学习.    一.平均传输延时 平均传输延时 二.开启时间与关闭时间 开 ...

  10. leetcode记录-罗马数字转整数

    罗马数字包含以下七种字符: I, V, X, L,C,D 和 M. 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 例如, 罗马数字 2 写做 II ,即为两个并 ...