Hadoop 3.x(MapReduce)----【MapReduce 概述】

发布于:2022-11-29 ⋅ 阅读:(660) ⋅ 点赞:(0)

1. MapReduce定义

MapReduce 是一个分布式运算程序的编程框架,是用户开发“基于 Hadoop 的数据分析应用”的核心框架。

MapReduce 核心功能是将用户编写的业务逻辑代码自带默认组件整合成一个完整的分布式运算程序,并发运行在一个 Hadoop 集群上。

在这里插入图片描述

2. MapReduce优缺点

1. 优点

  1. MapReduce 易于编程

它简单的实现一些接口,就可以完成一个分布式程序,这个分布式程序可以分布到大量廉价的 PC 机器上运行。也就是说你写一个分布式程序,跟写一个简单的串行程序时一模一样的。就是因为这个特点使得 MapReduce 编程变得非常流行。

  1. 良好的扩展性

当你的计算机资源不能得到满足的时候,你可以通过简单的增加机器来扩展它的计算能力。

  1. 高容错性

MapReduce 设计的初衷就是使程序能够部署在廉价的 PC 机器上,这就要求它具有很高的容错性。比如其中一台机器挂掉了,它可以把上面的计算任务转移到另外一个节点上运行,不至于这个任务运行失败,而且这个过程不需要人工参与,而完全是由 Hadoop 内部完成的。

  1. 适合 PB 级以上海量数据的离线处理

可以实现上千台服务器群并发工作,提供数据处理能力。

2. 缺点

  1. 不擅长实时计算

MapReduce 无法像 MySql 一样,在毫秒或者秒级内返回结果。

  1. 不擅长流式计算

流式计算的输入数据是动态的,而 MapReduce 的输入数据集是静态的,不能动态变化。这是因为 MapReduce 自身的设计特点决定了数据源必须是静态的。

  1. 不擅长 DAG(有向无环图)计算

多个应用程序存在依赖关系,后一个应用程序的输入为前一个的输出。在这种情况下,MapReduce 并不是不能做,而是使用后,每个 MapReduce 作业的输出结果都会写入到磁盘,会造成大量的磁盘 IO,导致性能非常的低下

3. MapReduce核心思想

在这里插入图片描述

  1. 分布式的运算程序往往需要分成至少 2 个阶段
  2. 第一个阶段的 MapTask 并发实例,完全并行运行,互不相干。
  3. 第二个阶段的 ReduceTask 并发实例互不相干,但是他们的数据依赖于上一个阶段的所有 MapTask 并发实例的输出。
  4. MapReduce 编程模型只能包含一个 Map 阶段和一个 Reduce 阶段,如果用户的业务逻辑非常复杂,那么就只能多个 MapReduce 程序,串行运行。

总结:分析 WordCount 数据流走向深入理解 MapReduce 核心思想。

4. MapReduce进程

一个完整的 MapReduce 程序在分布式运行时有三类实例进程:

  1. MrAppMaster:负责整个程序的过程调度及状态协调。
  2. MapTask:负责 Map 阶段的整个数据处理流程。
  3. ReduceTask:负责 Reduce 阶段的整个数据处理流程。

5. 官方WordCount源码

package org.apache.hadoop.examples;

import java.io.IOException;
import java.io.PrintStream;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Reducer.Context;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class WordCount
{
  public static void main(String[] args)
    throws Exception
  {
    Configuration conf = new Configuration();
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
    if (otherArgs.length < 2) {
      System.err.println("Usage: wordcount <in> [<in>...] <out>");
      System.exit(2);
    }
    Job job = Job.getInstance(conf, "word count");
    job.setJarByClass(WordCount.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    for (int i = 0; i < otherArgs.length - 1; i++) {
      FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
    }
    FileOutputFormat.setOutputPath(job, new Path(otherArgs[(otherArgs.length - 1)]));

    System.exit(job.waitForCompletion(true) ? 0 : 1);
  }

  public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable>
  {
    private IntWritable result = new IntWritable();

    public void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context)
      throws IOException, InterruptedException
    {
      int sum = 0;
      for (IntWritable val : values) {
        sum += val.get();
      }
      this.result.set(sum);
      context.write(key, this.result);
    }
  }

  public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable>
  {
    private static final IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(Object key, Text value, Mapper<Object, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException
    {
      StringTokenizer itr = new StringTokenizer(value.toString());
      while (itr.hasMoreTokens()) {
        this.word.set(itr.nextToken());
        context.write(this.word, one);
      }
    }
  }
}

6. 常用数据序列化类型

在这里插入图片描述

7. MapReduce编程规范

用户编写的程序分为三个部分:Mapper、Reducer、Driver。

1. Mapper阶段

  1. 用户自定义的 Mapper 要继承自己的父类
  2. Mapper 的输入数据是 KV 对的形式(KV 的类型可自定义)
  3. Mapper 中的业务逻辑写在 map() 方法中
  4. Mapper 的输出数据是 KV 对的形式(KV 的类型可自定义)
  5. map() 方法(MapTask 进程)对每一个 <K, V> 调用一次

2. Reducer阶段

  1. 用户自定义的 Reducer 要继承自己的父类
  2. Reducer 的输入数据类型对应 Mapper 的输出数据类型,也是 KV
  3. Reducer 的业务逻辑写在 reduce() 方法中
  4. ReduceTask 进程对每一组相同 k 的 <k, v> 组调用一次 reduce() 方法

3. Driver阶段

相当于 YARN 集群的客户端,用于提交我们整个程序到 YARN 集群,提交的是封装了 MapReduce 程序相关运行参数的 job 对象

8. WordCount案例实操

1. 本地测试

  1. 需求

在给定的文本文件中统计输出每一个单词出现的总次数

输入数据
在这里插入图片描述

期望输出数据

fickler		2
aaa		1
bbb		1
ccc		1
hadoop		2
  1. 需求分析

按照 MapReduce 编程规范,分别编写 Mapper,Reducer,Driver。

在这里插入图片描述

  1. 环境准备

创建 maven 工程,MapReduceDemo
在 pom.xml 文件中添加如下依赖

    <dependencies>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>3.1.3</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.30</version>
        </dependency>
    </dependencies>

在项目的 src/main/resources 目录下,新建一个文件,命名为 “log4j.properties”,在文件中填充。

log4j.rootLogger=INFO, stdout 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n 
log4j.appender.logfile=org.apache.log4j.FileAppender 
log4j.appender.logfile.File=target/spring.log 
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout 
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

创建包名:com.fickler.mapreduce.wordcount

  1. 编写程序

编写 Mapper 类

package com.fickler.mapreduce.wordcount;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/**
 * @author dell
 * @version 1.0
 * KEYIN,map阶段输入的key类型:LongWritable
 * VALUEIN,map阶段输入value的类型:Text
 * KEYOUT,map阶段输出的key类型:Text
 * VALUEOUT,map阶段输出的value类型:IntWritable
 */
public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {

    Text text = new Text();
    IntWritable intWritable = new IntWritable(1);

    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {

        //获取一行
        String string = value.toString();
        System.out.println(string);
        //切割
        String[] split = string.split(" ");
        //循环写入
        for(String word : split){
            //封装
            text.set(word);
            //写出
            context.write(text, intWritable);
        }

    }
}

编写 Reducer 类

package com.fickler.mapreduce.wordcount;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * @author dell
 * @version 1.0
 * KEYIN,reduce阶段输入的key类型:Text
 * VALUEIN,reduce阶段输入value的类型:IntWritable
 * KEYOUT,reduce阶段输出的key类型:Text
 * VALUEOUT,reduce阶段输出的value类型:IntWritable
 */
public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

    IntWritable intWritable = new IntWritable();

    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {

        int sum = 0;
        //累加
        for (IntWritable value : values) {
            sum += value.get();
        }

        intWritable.set(sum);

        //写出
        context.write(key, intWritable);

    }
}

编写 Driver 类

package com.fickler.mapreduce.wordcount;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @author dell
 * @version 1.0
 */
public class WordCountDriver {

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {

        //获取job
        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration);
        //设置jar包路径
        job.setJarByClass(WordCountDriver.class);
        //关联mapper和reducer
        job.setMapperClass(WordCountMapper.class);
        job.setReducerClass(WordCountReducer.class);
        //设置map输出的key,value输出类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        //设置最终输出的key,value类型
        job.setOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        //设置输入路径和输出路径
        FileInputFormat.setInputPaths(job, new Path("C:\\Users\\dell\\Desktop\\input"));
        FileOutputFormat.setOutputPath(job, new Path("C:\\Users\\dell\\Desktop\\output"));
        //提交job
        boolean result = job.waitForCompletion(true);
        System.exit(result ? 0 : 1);

    }

}

  1. 本地测试

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

2. 提交到集群测试

  1. 用 maven 打 jar 包,需要添加的打包插件依赖
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
  1. 将程序打成 jar 包

在这里插入图片描述

  1. 将不带依赖的 jar 包,拷贝到 Hadoop 集群的 /opt/module/hadoop-3.1.3 路径。
  2. 执行 WordCount 程序
[fickler@hadoop102 hadoop-3.1.3]$ hadoop jar MapReduceDemo-1.0-SNAPSHOT.jar com/fickler/mapreduce/wordcount2/WordCountDriver.java:41 /input /output

在这里插入图片描述

本文含有隐藏内容,请 开通VIP 后查看