Hadoop 从 0 到 1 学习 ——第十一章 MapReduce 框架原理

文章目录

1. InputFormat 数据输入

1.1 切片与 MapTask 并行度决定机制

  1. 问题引出

    MapTask 的并行度决定 Map阶段 的任务处理并发度,进而影响到整个 Job 的处理速度。

    思考:1G 的数据,启动 8 个 MapTask,可以提高集群的并发处理能力。那么 1K 的数据,也启动 8 个 MapTask,会提高集群性能吗?MapTask 并行任务是否越多越好呢?哪些因素影响了 MapTask 并行度?

  2. MapTask 并行度决定机制

    **数据块:**Block 是 HDFS 物理上把数据分成一块一块。

    **数据切片:**数据切片只是在逻辑上对输入进行分片,并不会在磁盘上将其切分成片进行存储。

    在这里插入图片描述

    MapTask 并行度决定机制

1.2 Job 提交流程源码和切片源码详解

waitForCompletion()

submit();

// 1建立连接
connect();	
// 1)创建提交Job的代理
new Cluster(getConfiguration());
// (1)判断是本地yarn还是远程
initialize(jobTrackAddr, conf); 

// 2 提交job
submitter.submitJobInternal(Job.this, cluster)
// 1)创建给集群提交数据的Stag路径
Path jobStagingArea = JobSubmissionFiles.getStagingDir(cluster, conf);

// 2)获取jobid ,并创建Job路径
JobID jobId = submitClient.getNewJobID();

// 3)拷贝jar包到集群
copyAndConfigureFiles(job, submitJobDir);	
rUploader.uploadFiles(job, jobSubmitDir);

// 4)计算切片,生成切片规划文件
writeSplits(job, submitJobDir);
maps = writeNewSplits(job, jobSubmitDir);
input.getSplits(job);

// 5)向Stag路径写XML配置文件
writeConf(conf, submitJobFile);
conf.writeXml(out);

// 6)提交Job,返回提交状态
status = submitClient.submitJob(jobId, submitJobDir.toString(), job.getCredentials());
  1. Job 提交流程源码解析

在这里插入图片描述

Job 提交流程源码分析
  1. 建立连接

  2. 创建提交 job 的代理

  3. 判断是本地 yarn 还是远程

  4. 提交 job

  5. 创建给集群提交数据的 Stag 路径

  6. 获取 jobid ,并创建 Job 路径

  7. 拷贝jar包到集群

  8. 计算切片,生成切片规划文件

  9. 向Stag路径写XML配置文件

  10. 提交Job,返回提交状态

  11. FileInputFormat 切片源码解析(input.getSplits(job))

    1. 程序先找到数据存储的目录

    2. 开始变量处理(规划切片)目录下的每个文件

    3. 遍历第一个文件 ss.txt

      a)获取文件大小 fs.sizeOf(ss.txt)

      b)计算切片大小

      computeSplitSize(Math.max(minSize, Math.min(maxSize, blockSize))) = blockSize = 128M

      c)默认情况下,切片大小=blockSize。

      d)开始切,形成第1个切片:ss.txt—0:128M,第2个切片:ss.txt—128:256M, 第3个切片ss.txt—256:300M

      e)将切片信息写到一个气派规划文件中

      f)整个切片的核心过程在 getSplit()方法中完成

      g) InputSplit只记录了切片的元数据信息,比如起始位置、长度以及所在的节点列表等。

    4. 提交切片规划文件到 YARN 上,YARN 上的 MrAppMaster 就可以根据切片规划文件计算开启 MapTask 个数。

1.3 FileInputFormat 切片机制

1.3.1 切片机制

  1. 简单的按照文件的内容长度进行切片
  2. 切片大小默认等于 block 大小
  3. 切片时不考虑数据集整体,而是组个针对每个文件单独切片

1.3.2 案例分析

  1. 输入数据有两个文件:

    file1.txt	320M
    file2.txt	10M
    
  2. 经过 FileInoutFormat 的切片机制运算后,形成的切片信息如下:

    file1.txt.split1——	0~128
    file1.txt.split2——	128~256M
    file1.txt.split3——	256~320M
    file2.txt.split1——	0~10M
    

1.3.3 FileInputFormat 切片大小的参数配置

  1. 源码中计算切片大小的公式

    Math.max(minSize,Math.min(maxSize, blockSize));
    
    #默认值为1
    mapreduce.input.fileinputformat.split.minsize=1 
    #默认值为 Long.MAXValue
    mapreduce.input.fileinputformat.split.maxsize=Long.MAXValue
    

    因此,默认情况下,切片大小=blocksize

  2. 切片大小设置

    maxsize(切片最大值):参数如果调的比 blocksize 小,则会让切片变小,而且就等于配置的这个参数的值。

    minsize(切片最小值):参数调的比 blocksize 大,则可以让切片变得比 blocksize 还大。

  3. 获取切片信息 API

    // 获取切片的文件名称
    String name = inputSplit.getPath().getName();
    // 根据文件类型获取切片信息
    FileSplit inputSplit = (FileSplit)context.getInputSplit();
    

1.4 CombineTextInputFormat 切片机制

框架默认的 TextInputFormat切片机制是对任务按文件规划切片,不管文件多小,都会是一个单独的切片,都会交给一个 MapTask,这样如果有大量小文件,就会产生大量的 MapTask,处理效率极其低下

1.4.1 应用场景

CombineTextInputFormat用于小文件过多的场景,它可以将多个小文件从逻辑上规划到一个切片中,这样,多个小文件就可以交给一个 MapTask 处理。

1.4.2 虚拟存储切片最大值设置

CombineTextInputFormat.setMaxInputSplitSize(job, 4194304);// 4m

1.4.3 切片机制

生成切片过程包括:虚拟存储过程和切片过程二部分。

CombineTextInputFormat切片机制

在这里插入图片描述

  1. 虚拟存储过程:

    将输入目录下所有文件大小,依次和设置的 setMaxInputSplitSize值比较,如果不大于设置的最大值,逻辑上划分一个块。如果输入文件大于设置的最大值且大于两倍,那么以最大值切割一块;当剩余数据大小超过设置的最大值且不大于最大值2倍,此时将文件均分成2个虚拟存储块(防止出现太小切片)

    例如 setMaxInputSplitSize值为 4M,输入文件大小为 8.02M,则先逻辑上分成一个4M。剩余的大小为4.02M,如果按照4M逻辑划分,就会出现0.02M的小的虚拟存储文件,所以将剩余的4.02M文件切分成(2.01M和2.01M)两个文件。

  2. 切片过程:

    (a)判断虚拟存储的文件大小是否大于setMaxInputSplitSize值,大于等于则单独形成一个切片。

    (b)如果不大于则跟下一个虚拟存储文件进行合并,共同形成一个切片。

    (c)测试举例:有4个小文件大小分别为1.7M5.1M3.4M以及6.8M这四个小文件,则虚拟存储之后形成6个文件块,大小分别为:

    1.7M,(2.55M、2.55M),3.4M以及(3.4M、3.4M)

    ​ 最终会形成3个切片,大小分别为:

    (1.7+2.55)M,(2.55+3.4)M,(3.4+3.4)M

1.5 CombineTextInputFormat 案例操作

1.5.1 需求

将输入的大量小文件合并成一个切片统一处理。

  1. 输入数据

    准备4个小文件

  2. 期望

    期望一个切片处理4个文件

1.5.2 实现过程

  1. 不做任何处理,运行1.6节的WordCount案例程序,观察切片个数为4。

    number of splits:4
    
  2. 在WordcountDriver中增加如下代码,运行程序,并观察运行的切片个数为3。

    (a) 驱动类中添加如下代码:

    // 如果不设置InputFormat,它默认用的是TextInputFormat.class
    job.setInputFormatClass(CombineTextInputFormat.class);
    
    //虚拟存储切片最大值设置4m
    CombineTextInputFormat.setMaxInputSplitSize(job, 4194304);
    

    (b) 运行结果为 个切片。

    number of splits:3
    
  3. 在WordcountDriver中增加如下代码,运行程序,并观察运行的切片个数为1。

    (a) 驱动中添加代码如下:

    // 如果不设置InputFormat,它默认用的是TextInputFormat.class
    job.setInputFormatClass(CombineTextInputFormat.class);
    
    //虚拟存储切片最大值设置20m
    CombineTextInputFormat.setMaxInputSplitSize(job, 20971520);
    

    (b) 运行结果为 1 个切片

    number of splits:1
    

1.6 FileInputFormat 实现类

思考:在运行 MapReduce 程序时,输入的文件格式包括:基于行的日志文件,二进制格式文件、数据库表等。那么,针对不同的数据类型,MapReduce 是如何读取这些数据的呢?

FileInputFormat常见的接口实现类包括:TextInputFormatKeyValueTextInputFormatNLineInputFormatCombineTextInputFormat自定义 InputFormat等。

  1. TextInputFormat

    TextInputForamt 是默认的 FileInputFormat 实现类。按行读取每条记录。键是存储该行在整个文件中的起始字节偏移量,LongWritable 类型。值是这行的内容,不包括这行的任何行终止符(换行符和回车符),Text 类型。

    以下是一个示例,比如一个分片包含了如下4条文本记录。

    java spark
    flink hadoop
    hive java
    scala python
    

    每条记录表示为以下键值对:

    (0,java spark)
    (10,flink hadoop)
    (22,hive java)
    (31,scala python)
    
  2. KeyValueTextInputFormat

    每一行均为一条记录,被分隔符分割为 key,value。可以通过在驱动类中设置jobConf.set(org.apache.hadoop.mapreduce.lib.input.KeyValueLineRecordReader.KEY_VALUE_SEPERATOR,"\t");来设定分隔符。默认分隔符是 tab(\t)。

    以下是一个示例,输入是一个包含 4 条记录的分片。其中 ——> 表示一个 (水平方法的) 制表符。

    line1 ——>java spark
    line2 ——>flink hadoop
    line3 ——>hive java
    line4 ——>scala python
    

    每条记录表示为以下键值对:

    (line1,java spark)
    (line2,flink hadoop)
    (line3,hive java)
    (line4,scala python)
    

    此时的键是每行排在制表符之前的 Text 序列。

  3. NLineTextInputFormat

    如果使用 NLineInputFormat,代表每个 map 进程处理的 InputSplit 不再按 Block 块去划分,而是按 NLineTextInputFormat 指定的行数N 来划分。即输入文件的总行数/N = 切片数,如果不整除,切片数=商+1

    以下是一个示例,仍然以上面的4行数据输入为例:

    java spark
    flink hadoop
    hive java
    scala python
    

    例如,如果 N 是 2,则每个输入分片包含两行。开启 2个 MapTask。

    (0,java spark)
    (10,flink hadoop)
    

    另一个 mapper 则收到后两行:

    (22,hive java)
    (31,scala python)
    

    这里的键和值与 TextInputForamt生成的一样。

1.7 KeyValueTextInputFormat 使用案例

1.7.1 需求

统计输入文件中每行的第一个单词相同的行数。

  1. 输入数据

    banzhang ni hao
    xihuan hadoop banzhang
    banzhang ni hao
    xihuan hadoop banzhang
    
  2. 期望结果数据

    banzhang	2
    xihuan	2
    

1.7.2 需求分析

KeyValueTextInputFormat 案例分析

在这里插入图片描述

1.7.3 代码实现

  1. 编写 Mapper 类

    package com.bigdata.hadoop.mapreduce.KeyValueTextInputFormat;
    import java.io.IOException;
    import org.apache.hadoop.io.LongWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Mapper;
    
    public class KVTextMapper extends Mapper<Text, Text, Text, LongWritable>{
          
          
        // 1 设置value
        LongWritable v = new LongWritable(1);  
        
    	@Override
    	protected void map(Text key, Text value, Context context)
    			throws IOException, InterruptedException {
          
          
            // banzhang ni hao
          
            // 2 写出
            context.write(key, v);  
    	}
    }
    
  2. 编写 Reducer 类

    package com.bigdata.hadoop.mapreduce.KeyValueTextInputFormat;
    import java.io.IOException;
    import org.apache.hadoop.io.LongWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Reducer;
    
    public class KVTextReducer extends Reducer<Text, LongWritable, Text, LongWritable>{
          
          
    	
        LongWritable v = new LongWritable();  
        
    	@Override
    	protected void reduce(Text key, Iterable<LongWritable> values,	Context context) throws IOException, InterruptedException {
          
          
    		
    		 long sum = 0L;  
    
    		 // 1 汇总统计
            for (LongWritable value : values) {
          
            
                sum += value.get();  
            }
             
            v.set(sum);  
             
            // 2 输出
            context.write(key, v);  
    	}
    }
    
  3. 编写 Driver 类

    package com.bigdata.hadoop.mapreduce.KeyValueTextInputFormat;
    import java.io.IOException;
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.LongWritable;
    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.input.KeyValueLineRecordReader;
    import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
    import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
    
    public class KVTextDriver {
          
          
    
    	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
          
          
    		
    		Configuration conf = new Configuration();
    		// 设置切割符
            conf.set(KeyValueLineRecordReader.KEY_VALUE_SEPERATOR, " ");
    		// 1 获取job对象
    		Job job = Job.getInstance(conf);
    		
    		// 2 设置jar包位置,关联mapper和reducer
    		job.setJarByClass(KVTextDriver.class);
    		job.setMapperClass(KVTextMapper.class);
            job.setReducerClass(KVTextReducer.class);
    				
    		// 3 设置map输出kv类型
    		job.setMapOutputKeyClass(Text.class);
    		job.setMapOutputValueClass(LongWritable.class);
    
    		// 4 设置最终输出kv类型
    		job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(LongWritable.class);
    		
    		// 5 设置输入输出数据路径
    		FileInputFormat.setInputPaths(job, new Path(args[0]));
    		
    		// 设置输入格式
            job.setInputFormatClass(KeyValueTextInputFormat.class);
    		
    		// 6 设置输出数据路径
    		FileOutputFormat.setOutputPath(job, new Path(args[1]));
    		
    		// 7 提交job
    		job.waitForCompletion(true);
    	}
    }
    

1.8 NLineInputFormat使用案例

1.8.1 需求

对每个单词进行个数统计,要求根据每个输入文件的行数来规定输出多少个切片。此案例要求每三行放入一个切片中。

  1. 输入数据:

    banzhang ni hao
    xihuan hadoop banzhang
    banzhang ni hao
    xihuan hadoop banzhang
    banzhang ni hao
    xihuan hadoop banzhang
    banzhang ni hao
    xihuan hadoop banzhang
    banzhang ni hao
    xihuan hadoop banzhang banzhang ni hao
    xihuan hadoop banzhang
    
  2. 期望输出数据:

    Number of splits:4
    

1.8.2 需求分析

NLineInputFormat 案例分析

在这里插入图片描述

1.8.3 代码实现

  1. 编写 Mapper 类

    package com.bigdata.hadoop.mapreduce.nline;
    
    import java.io.IOException;
    import org.apache.hadoop.io.LongWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Mapper;
    
    public class NLineMapper extends Mapper<LongWritable, Text, Text, LongWritable>{
          
          
    
        private Text k = new Text();
        private LongWritable v = new LongWritable(1);
    
        @Override
        protected void map(LongWritable key, Text value, Context context)	throws IOException, InterruptedException {
          
          
    
            // 1 获取一行
            String line = value.toString();
    
            // 2 切割
            String[] splited = line.split(" ");
    
            // 3 循环写出
            for (int i = 0; i < splited.length; i++) {
          
          
    
                k.set(splited[i]);
    
                context.write(k, v);
            }
        }
    }
    
  2. 编写 Reducer 类

    package com.bigdata.hadoop.mapreduce.nline;
    
    import java.io.IOException;
    import org.apache.hadoop.io.LongWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Reducer;
    
    public class NLineReducer extends Reducer<Text, LongWritable, Text, LongWritable>{
          
          
    
        LongWritable v = new LongWritable();
    
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values,	Context context) throws IOException, InterruptedException {
          
          
    
            long sum = 0L;
    
            // 1 汇总
            for (LongWritable value : values) {
          
          
                sum += value.get();
            }
    
            v.set(sum);
    
            // 2 输出
            context.write(key, v);
        }
    }
    
  3. 编写 Driver 类

    package com.bigdata.hadoop.mapreduce.nline;
    
    import java.io.IOException;
    import java.net.URISyntaxException;
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.LongWritable;
    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.input.NLineInputFormat;
    import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
    
    public class NLineDriver {
          
          
        public static void main(String[] args) throws IOException, URISyntaxException, ClassNotFoundException, InterruptedException {
          
          
    
            // 输入输出路径需要根据自己电脑上实际的输入输出路径设置
            args = new String[] {
          
           "e:/input/inputword", "e:/output1" };
    
            // 1 获取job对象
            Configuration configuration = new Configuration();
            Job job = Job.getInstance(configuration);
    
            // 7设置每个切片InputSplit中划分三条记录
            NLineInputFormat.setNumLinesPerSplit(job, 3);
    
            // 8使用NLineInputFormat处理记录数
            job.setInputFormatClass(NLineInputFormat.class);
    
            // 2设置jar包位置,关联mapper和reducer
            job.setJarByClass(NLineDriver.class);
            job.setMapperClass(NLineMapper.class);
            job.setReducerClass(NLineReducer.class);
    
            // 3设置map输出kv类型
            job.setMapOutputKeyClass(Text.class);
            job.setMapOutputValueClass(LongWritable.class);
    
            // 4设置最终输出kv类型
            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(LongWritable.class);
    
            // 5设置输入输出数据路径
            FileInputFormat.setInputPaths(job, new Path(args[0]));
            FileOutputFormat.setOutputPath(job, new Path(args[1]));
    
            // 6提交job
            job.waitForCompletion(true);
        }
    
    }
    

1.9 自定义 InputFormat

在企业开发中,Hadoop 框架自带的 InputForamt 类型不能满足所有应用场景,需要自定义 InputFormat 来解决实际问题。

自定义 InputFormat 步骤如下:

  1. 自定义一个类继承 FileInputFormat
  2. 改写 RecordReader,实现一次读取一个完整文件封装为KV。
  3. 在输出时使用 mermaid sequenceDiagramFileOutPutFormat输出合并文件。

1.10 自定义 InputFormat 案例操作

无论 HDFS 还是 MapReduce,在处理小文件时效率都非常低,但又难免面临处理大量小文件的场景,此时,就需要有相应解决方案。可以自定义 InputFormat 实现小文件的合并。

1.10.1 需求

将多个小文件合并成一个 SequenceFile 文件( SequenceFile 文件是 Hadoop 用来存储二进制形式的 key-value 对的文件格式),SequenceFile 里面存储着多个文件,存储的形式为文件路径+名称为 key,文件内容为 value。

1.10.2 需求分析

自定义 InputFormat 案例分析

在这里插入图片描述

1.10.3 代码实现

  1. 自定义 InputFromat

    package com.bigdata.hadoop.mapreduce.inputformat;
    
    import java.io.IOException;
    
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.BytesWritable;
    import org.apache.hadoop.io.NullWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.InputSplit;
    import org.apache.hadoop.mapreduce.JobContext;
    import org.apache.hadoop.mapreduce.RecordReader;
    import org.apache.hadoop.mapreduce.TaskAttemptContext;
    import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
    
    
    /**
     * 自定义 InputFormat 继承 FileInputFormat
     */
    public class WholeFileInputformat extends FileInputFormat<Text, BytesWritable> {
          
          
    
        @Override
        protected boolean isSplitable(JobContext context, Path filename) {
          
          
            return false;
        }
    
        @Override
        public RecordReader<Text, BytesWritable> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
          
          
    
            WholeRecordReader recordReader = new WholeRecordReader();
            recordReader.initialize(split, context);
    
            return recordReader;
        }
    
    }
    
  2. 自定义 RecordReader

    package com.bigdata.hadoop.mapreduce.inputformat;
    
    import java.io.IOException;
    
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.FSDataInputStream;
    import org.apache.hadoop.fs.FileSystem;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.BytesWritable;
    import org.apache.hadoop.io.IOUtils;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.InputSplit;
    import org.apache.hadoop.mapreduce.RecordReader;
    import org.apache.hadoop.mapreduce.TaskAttemptContext;
    import org.apache.hadoop.mapreduce.lib.input.FileSplit;
    
    
    public class WholeRecordReader extends RecordReader<Text, BytesWritable> {
          
          
    
        private Configuration configuration;
        private FileSplit split;
    
        private boolean isProgress = true;
        private BytesWritable value = new BytesWritable();
        private Text k = new Text();
    
        @Override
        public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
          
          
    
            this.split = (FileSplit) split;
            configuration = context.getConfiguration();
        }
    
        @Override
        public boolean nextKeyValue() throws IOException, InterruptedException {
          
          
    
            if (isProgress) {
          
          
    
                // 1 定义缓存区
                byte[] contents = new byte[(int) split.getLength()];
    
                FileSystem fs = null;
                FSDataInputStream fis = null;
    
                try {
          
          
                    // 2 获取文件系统
                    fs = FileSystem.get(configuration);
    
                    // 3 读取数据
                    Path path = split.getPath();
                    fis = fs.open(path);
    
                    // 4 读取文件内容
                    IOUtils.readFully(fis, contents, 0, contents.length);
    
                    // 5 输出文件内容
                    value.set(contents, 0, contents.length);
    
                    // 6 获取文件路径及名称
                    String name = split.getPath().toString();
    
                    // 7 设置输出的key值
                    k.set(name);
    
                } catch (Exception e) {
          
          
    
                } finally {
          
          
                    IOUtils.closeStream(fis);
                }
    
                isProgress = false;
    
                return true;
            }
    
            return false;
        }
    
        @Override
        public Text getCurrentKey() throws IOException, InterruptedException {
          
          
            return k;
        }
    
        @Override
        public BytesWritable getCurrentValue() throws IOException, InterruptedException {
          
          
            return value;
        }
    
        @Override
        public float getProgress() throws IOException, InterruptedException {
          
          
            return 0;
        }
    
        @Override
        public void close() throws IOException {
          
          
        }
    }
    
  3. 编写 mermaid sequenceDiagramFileMapper类处理流程

    package com.bigdata.hadoop.mapreduce.inputformat;
    
    import org.apache.hadoop.io.BytesWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Mapper;
    
    import java.io.IOException;
    
    public class SequenceFileMapper extends Mapper<Text, BytesWritable, Text, BytesWritable> {
          
          
    
        @Override
        protected void map(Text key, BytesWritable value, Context context) throws IOException, InterruptedException {
          
          
    
            context.write(key, value);
        }
    }
    
  4. 编写 mermaid sequenceDiagramFileReducer类处理流程

    package com.bigdata.hadoop.mapreduce.inputformat;
    
    import java.io.IOException;
    
    import org.apache.hadoop.io.BytesWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Reducer;
    
    public class SequenceFileReducer extends Reducer<Text, BytesWritable, Text, BytesWritable> {
          
          
    
        @Override
        protected void reduce(Text key, Iterable<BytesWritable> values, Context context) throws IOException, InterruptedException {
          
          
    
            context.write(key, values.iterator().next());
        }
    }
    
  5. 编写 mermaid sequenceDiagramFileDriver类处理流程

    package com.bigdata.hadoop.mapreduce.inputformat;
    
    import java.io.IOException;
    
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.BytesWritable;
    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 org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
    
    public class SequenceFileDriver {
          
          
    
        public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
          
          
    
            // 输入输出路径需要根据自己电脑上实际的输入输出路径设置
            args = new String[]{
          
          "e:/input/inputinputformat", "e:/output1"};
    
            // 1 获取job对象
            Configuration conf = new Configuration();
            Job job = Job.getInstance(conf);
    
            // 2 设置jar包存储位置、关联自定义的mapper和reducer
            job.setJarByClass(SequenceFileDriver.class);
            job.setMapperClass(SequenceFileMapper.class);
            job.setReducerClass(SequenceFileReducer.class);
    
            // 7设置输入的inputFormat
            job.setInputFormatClass(WholeFileInputformat.class);
    
            // 8设置输出的outputFormat
            job.setOutputFormatClass(SequenceFileOutputFormat.class);
    
    		// 3 设置map输出端的kv类型
            job.setMapOutputKeyClass(Text.class);
            job.setMapOutputValueClass(BytesWritable.class);
    
            // 4 设置最终输出端的kv类型
            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(BytesWritable.class);
    
            // 5 设置输入输出路径
            FileInputFormat.setInputPaths(job, new Path(args[0]));
            FileOutputFormat.setOutputPath(job, new Path(args[1]));
    
            // 6 提交job
            boolean result = job.waitForCompletion(true);
            System.exit(result ? 0 : 1);
        }
    }
    

2. MapReuce 工作流程

2.1 流程示意图

在这里插入图片描述

MapReduce 详细工作流程(一)

在这里插入图片描述

MapReduce 详细工作流程(二)

2.2 流程详解

上面的流程是整个 MapReduce 最全工作流程,但是 Shuffle 过程只是从第7步开始到第16步结束,具体 Shuffle 过程详解,如下:

  1. MapTask 收集我们的 map()方法输出的kv对,放到内存缓冲区中

  2. 从内存缓冲区不断溢出本地磁盘文件,可能会溢出多个文件

  3. 多个溢出文件会被合并成大的溢出文件

  4. 在溢出过程及合并的过程中,都要调用 Partitioner 进行分区和针对 key 进行排序

  5. ReduceTask 根据自己的分区号,去各个 MapTask 机器上取相应的结果分区数据

  6. ReduceTask 会取到同一个分区的来自不同 MapTask 的结果文件,ReduceTask 会将这些文件再进行合并(归并排序)

  7. 合并成大文件后,Shuffle 的过程也就结束了,后面进入 ReduceTask 的逻辑运算过程(从文件中取出一个一个的键值对 Group,调用用户自定义的reduce()方法)

2.3 注意

Shuffle 中的缓冲区大小会影响到 MapReduce 程序的执行效率,原则上说,缓冲区越大,磁盘io 的次数越少,执行速度就越快。

缓冲区的大小可以通过参数调整,参数:io.sort.mb默认100M。

3. Shuffle 机制

3.1 Shuffle 机制

Map 方法之后,Reduce 方法之前的数据处理过程称之为 Shuffle。如图所示:

在这里插入图片描述

Shuffle 机制

3.2 Partition 分区

3.2.1 问题引出

要求将统计结果按照条件输出到不同文件中(分区)。比如:将统计结果按照手机归属地不同省份输出到不同文件中(分区)。

3.2.2 默认 Partitioner 分区

public class HashPartitioner<K, V> extends Partitioner<K, V> {
    
    
    public HashPartitioner() {
    
    
    }

    public int getPartition(K key, V value, int numReduceTasks) {
    
    
        return (key.hashCode() & 2147483647) % numReduceTasks;
    }
}

默认分区是根据 key 的 hashCode 对 ReduceTasks 个数取模得到的。用户没法控制哪个 key 存储到哪个分区。

3.2.3 自定义 Partitioner

  1. 自定义类继承 Partitioner,重写 getPartition()方法

    public class CustomPartitioner extends HashPartitioner<Text, FlowBean> {
          
          
    
        @Override
        public int getPartition(Text key, FlowBean value, int numReduceTasks) {
          
          
            // todo 控制分区代码逻辑
            return partition;
        }
    }
    
  2. 在 job 驱动中,设置自定义 Partitioner

    job.setPartitionerClass(CustomPartitioner.class);
    
  3. 自定义 Partition 后,要根据自定义 Partitioner 的逻辑设置相应数量的 ReduceTask

    job.setNumReduceTasks(5);
    

3.2.4 分区总结

  1. 如果 ReduceTask 的数量 > getPartition 的结果数,则会多产生几个空的输出文件。
  2. 如果 1 < ReduceTask 的数量 < getPartition 的结果数,则有一部分分区数据无处安放,会报异常。
  3. 如果 ReduceTask 的数量=1,则不管 MapTask 端输出多少个分区文件,最终都交给这一个 ReduceTask,最终也就只会产生一个结果文件。
  4. 分区号必须从零开始,逐一累加。

3.2.5 案例分析

假如:自定义分区数为 5;则:

  1. job.setNumReduceTasks(1):会正常运行,只不过会产生一个输出文件
  2. job.setNumReduceTasks(2):会报错
  3. job.setNumReduceTasks(6):大于5,程序会正常运行,会产生空文件

3.3 Partition分区案例实操

3.3.1 需求

将计算结果按照手机号归属地不同省份输出到不同文件中(分区)。

输入数据:

1	13736230513	192.196.100.1	www.apache.com	2481	24681	200
2	13846544121	192.196.100.2			264	0	200
3 	13956435636	192.196.100.3			132	1512	200
4 	13966251146	192.168.100.1			240	0	404
5 	18271575951	192.168.100.2	www.apache.com	1527	2106	200
6 	84188413	192.168.100.3	www.apache.com	4116	1432	200
7 	13590439668	192.168.100.4			1116	954	200
8 	15910133277	192.168.100.5	www.hao123.com	3156	2936	200
9 	13729199489	192.168.100.6			240	0	200
10 	13630577991	192.168.100.7	www.shouhu.com	6960	690	200
11 	15043685818	192.168.100.8	www.baidu.com	3659	3538	200
12 	15959002129	192.168.100.9	www.apache.com	1938	180	500
13 	13560439638	192.168.100.10			918	4938	200
14 	13470253144	192.168.100.11			180	180	200
15 	13682846555	192.168.100.12	www.qq.com	1938	2910	200
16 	13992314666	192.168.100.13	www.gaga.com	3008	3720	200
17 	13509468723	192.168.100.14	www.qinghua.com	7335	110349	404
18 	18390173782	192.168.100.15	www.sogou.com	9531	2412	200
19 	13975057813	192.168.100.16	www.baidu.com	11058	48243	200
20 	13768778790	192.168.100.17			120	120	200
21 	13568436656	192.168.100.18	www.alibaba.com	2481	24681	200
22 	13568436656	192.168.100.19			1116	954	200

期望输出数据:

手机号136、137、138、139开头都分别放到一个独立的4个文件中,其他开头的放到一个文件中。

3.3.2 需求分析

在这里插入图片描述

3.3.3 定义一个分区类

package com.bigdata.hadoop.mapreduce.flowsum;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Partitioner;

import java.util.HashMap;

/**
 * 根据手机号前三位分发不同的reduce程序,其输入结果是map的输出
 * @author dwjf321
 */
public class ProvincePartitioner implements Partitioner<FlowBean, Text> {
    
    

    public static HashMap<String, Integer> provinceDict = new HashMap<String, Integer>();
    static{
    
    
        provinceDict.put("136", 0);
        provinceDict.put("137", 1);
        provinceDict.put("138", 2);
        provinceDict.put("139", 3);
    }
    @Override
    public int getPartition(FlowBean key, Text value, int partition) {
    
    
        //根据手机号的前三位分区
        String phoneNum = value.toString().substring(0,3);
        Integer partitionId = provinceDict.get(phoneNum);
        return partitionId == null ? 4 : partitionId;
    }

    @Override
    public void configure(JobConf jobConf) {
    
    

    }
}

3.3.4 在驱动中添加自定义分区设置和 ReduceTask 设置

package com.bigdata.hadoop.mapreduce.flowsum;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
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;

public class FlowsumDriver {
    
    

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

		// 输入输出路径需要根据自己电脑上实际的输入输出路径设置
		args = new String[]{
    
    "e:/output1","e:/output2"};

		// 1 获取配置信息,或者job对象实例
		Configuration configuration = new Configuration();
		Job job = Job.getInstance(configuration);

		// 2 指定本程序的jar包所在的本地路径
		job.setJarByClass(FlowsumDriver.class);

		// 3 指定本业务job要使用的mapper/Reducer业务类
		job.setMapperClass(FlowCountMapper.class);
		job.setReducerClass(FlowCountReducer.class);

		// 4 指定mapper输出数据的kv类型
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(FlowBean.class);

		// 5 指定最终输出的数据的kv类型
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(FlowBean.class);

		// 8 指定自定义数据分区
		job.setPartitionerClass(ProvincePartitioner.class);

		// 9 同时指定相应数量的reduce task
		job.setNumReduceTasks(5);
		
		// 6 指定job的输入原始文件所在目录
		FileInputFormat.setInputPaths(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));

		// 7 将job中配置的相关参数,以及job所用的java类所在的jar包, 提交给yarn去运行
		boolean result = job.waitForCompletion(true);
		System.exit(result ? 0 : 1);
	}
}

3.4 WritableComparable 排序

3.4.1 排序概述

排序是 MapReduce 框架中最重要的操作之一。

MapTask 和 ReduceTask 都会对数据按照 key 进行排序。该操作数据 Hadoop 的默认行为。任何应用程序中的数据都会被排序,而不管逻辑上是否需要。

默认排序是按照字典顺序排序,且实现该排序的方法是快速排序

对于 MapTask,它会将处理结果暂时放到环形缓冲区,当环形缓冲区使用率达到一个阈值后,再对缓冲区中的数据进行一次快速排序,并将这些有序数据溢写到磁盘上,而当数据处理完毕之后,它会对磁盘上所有文件进行归并排序

对于 ReduceTask,它从每个 MapTask 上远程拷贝相应的数据文件,如果文件大小超过一定阈值,则溢写磁盘,否则存储在内存中。如果磁盘上文件数目大于一定阈值,则进行一次归并排序,生产一个更大的文件;如果内存中文件大小或者数目超过一定阈值,则进行一个合并后将数据溢写到磁盘上。当所有数据拷贝完毕后。ReduceTask 统一对内存和磁盘上的所有数据进行一次归并排序

3.4.2 排序的分类

  1. 部分排序

    MapReduce 根据输入数据的 Key(键)对数据集排序。保证输出的每个文件内部有序

  2. 全排序

    最终输出结果只有一个文件,且文件内部有序。实现方式是只设置一个 ReduceTask。但该方法在处理大型文件时效率极低。因为一台机器处理所有文件,完全丧失了 MapReduce 所提供的并行架构。

  3. 辅助排序(Grouping Comparator 分组)

    在 Reduce 端对 key 进行分组。应用于:在接收的 key 为bean 对象时,想让一个或者 几个字段相同(全部字段比较不同) 的 key 进入到同一个 reduce 方法时,可以采用分组排序。

  4. 二次排序

    在自定义排序过程中,如果 compareTo中判断的条件为 两个即为 二次排序。

3.4.3 自定义排序 WritableComparable

bean 对象作为 key 传输,需要实现 WritableComparable接口,并重写 compareTo方法,就可以实现排序。

@Override
public int compareTo(FlowBean o) {
    
    

	int result;
		
	// 按照总流量大小,倒序排列
	if (sumFlow > bean.getSumFlow()) {
    
    
		result = -1;
	}else if (sumFlow < bean.getSumFlow()) {
    
    
		result = 1;
	}else {
    
    
		result = 0;
	}

	return result;
}

3.5 WritableComparable排序案例实操(全排序)

3.5.1 需求

计算手机的总流量,并对总流量进行排序。

  1. 输入数据:

    1	13736230513	192.196.100.1	www.apache.com	2481	24681	200
    2	13846544121	192.196.100.2			264	0	200
    3 	13956435636	192.196.100.3			132	1512	200
    4 	13966251146	192.168.100.1			240	0	404
    5 	18271575951	192.168.100.2	www.apache.com	1527	2106	200
    6 	84188413	192.168.100.3	www.apache.com	4116	1432	200
    7 	13590439668	192.168.100.4			1116	954	200
    8 	15910133277	192.168.100.5	www.hao123.com	3156	2936	200
    9 	13729199489	192.168.100.6			240	0	200
    10 	13630577991	192.168.100.7	www.shouhu.com	6960	690	200
    11 	15043685818	192.168.100.8	www.baidu.com	3659	3538	200
    12 	15959002129	192.168.100.9	www.apache.com	1938	180	500
    13 	13560439638	192.168.100.10			918	4938	200
    14 	13470253144	192.168.100.11			180	180	200
    15 	13682846555	192.168.100.12	www.qq.com	1938	2910	200
    16 	13992314666	192.168.100.13	www.gaga.com	3008	3720	200
    17 	13509468723	192.168.100.14	www.qinghua.com	7335	110349	404
    18 	18390173782	192.168.100.15	www.sogou.com	9531	2412	200
    19 	13975057813	192.168.100.16	www.baidu.com	11058	48243	200
    20 	13768778790	192.168.100.17			120	120	200
    21 	13568436656	192.168.100.18	www.alibaba.com	2481	24681	200
    22 	13568436656	192.168.100.19			1116	954	200
    
  2. 期望输出数据

    13509468723	7335	110349	117684
    13736230513	2481	24681	27162
    13956435636	132		1512	1644
    13846544121	264		0		264
    

3.5.2 需求分析

WritableComparable 排序案例分析(全排序)

在这里插入图片描述

3.5.3 代码实现

  1. FlowBean 对象

    package com.bigdata.hadoop.mapreduce.sort;
    
    import org.apache.hadoop.io.WritableComparable;
    
    import java.io.DataInput;
    import java.io.DataOutput;
    import java.io.IOException;
    
    /**
     * 作为key输出的时候需要排序
     * 不排序的话,可以实现Writable
     * 实现WritableComparable是为了实现比较大小、排序功能
     * @author dwjf321
     */
    public class FlowBean implements WritableComparable<FlowBean> {
          
          
    
        private Long upFlow;
        private Long downFlow;
        private Long sumFlow;
    
        //反序列化的时候需要调用空构造函数,显示的定义一个
        public FlowBean(){
          
          }
    
        public FlowBean(Long upFlow, Long downFlow) {
          
          
            this.upFlow = upFlow;
            this.downFlow = downFlow;
            this.sumFlow = upFlow+downFlow;
        }
    
        public void set(long upFlow, long downFlow){
          
          
            this.upFlow = upFlow;
            this.downFlow = downFlow;
            this.sumFlow = upFlow+downFlow;
        }
        public Long getUpFlow() {
          
          
            return upFlow;
        }
    
        public void setUpFlow(Long upFlow) {
          
          
            this.upFlow = upFlow;
        }
    
        public Long getDownFlow() {
          
          
            return downFlow;
        }
    
        public void setDownFlow(Long downFlow) {
          
          
            this.downFlow = downFlow;
        }
    
        public Long getSumFlow() {
          
          
            return sumFlow;
        }
    
        public void setSumFlow(Long sumFlow) {
          
          
            this.sumFlow = sumFlow;
        }
    
    
    
        @Override
        public int compareTo(FlowBean bean) {
          
          
            return this.sumFlow > bean.sumFlow ? -1:1;
        }
    
        /**
         * 序列化
         * @param output
         * @throws IOException
         */
        @Override
        public void write(DataOutput output) throws IOException {
          
          
            output.writeLong(upFlow);
            output.writeLong(downFlow);
            output.writeLong(sumFlow);
        }
    
        /**
         * 反序列化
         * @param input
         * @throws IOException
         */
        @Override
        public void readFields(DataInput input) throws IOException {
          
          
            this.upFlow = input.readLong();
            this.downFlow = input.readLong();
            this.sumFlow = input.readLong();
        }
    
        @Override
        public String toString() {
          
          
            return upFlow + "\t" + downFlow + "\t" + sumFlow ;
        }
    }
    
  2. 编写 Mapper 类

    package com.bigdata.hadoop.mapreduce.sort;
    import java.io.IOException;
    import org.apache.hadoop.io.LongWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Mapper;
    
    public class FlowCountSortMapper extends Mapper<LongWritable, Text, FlowBean, Text>{
          
          
    
    	FlowBean bean = new FlowBean();
    	Text v = new Text();
    
    	@Override
    	protected void map(LongWritable key, Text value, Context context)	throws IOException, InterruptedException {
          
          
    
    		// 1 获取一行
    		String line = value.toString();
    		
    		// 2 截取
    		String[] fields = line.split("\t");
    		
    		// 3 封装对象
    		String phoneNbr = fields[0];
    		long upFlow = Long.parseLong(fields[1]);
    		long downFlow = Long.parseLong(fields[2]);
    		
    		bean.set(upFlow, downFlow);
    		v.set(phoneNbr);
    		
    		// 4 输出
    		context.write(bean, v);
    	}
    }
    
    
  3. 编写 Reducer 类

    package com.bigdata.hadoop.mapreduce.sort;
    import java.io.IOException;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Reducer;
    
    public class FlowCountSortReducer extends Reducer<FlowBean, Text, Text, FlowBean>{
          
          
    
    	@Override
    	protected void reduce(FlowBean key, Iterable<Text> values, Context context)	throws IOException, InterruptedException {
          
          
    		
    		// 循环输出,避免总流量相同情况
    		for (Text value : values) {
          
          
    			context.write(value, key);
    		}
    	}
    }
    
  4. 编写 Driver 类

    package com.bigdata.hadoop.mapreduce.sort;
    import java.io.IOException;
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.Path;
    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;
    
    public class FlowCountSortDriver {
          
          
    
    	public static void main(String[] args) throws ClassNotFoundException, IOException, InterruptedException {
          
          
    
    		// 输入输出路径需要根据自己电脑上实际的输入输出路径设置
    		args = new String[]{
          
          "e:/output1","e:/output2"};
    
    		// 1 获取配置信息,或者job对象实例
    		Configuration configuration = new Configuration();
    		Job job = Job.getInstance(configuration);
    
    		// 2 指定本程序的jar包所在的本地路径
    		job.setJarByClass(FlowCountSortDriver.class);
    
    		// 3 指定本业务job要使用的mapper/Reducer业务类
    		job.setMapperClass(FlowCountSortMapper.class);
    		job.setReducerClass(FlowCountSortReducer.class);
    
    		// 4 指定mapper输出数据的kv类型
    		job.setMapOutputKeyClass(FlowBean.class);
    		job.setMapOutputValueClass(Text.class);
    
    		// 5 指定最终输出的数据的kv类型
    		job.setOutputKeyClass(Text.class);
    		job.setOutputValueClass(FlowBean.class);
    
    		// 6 指定job的输入原始文件所在目录
    		FileInputFormat.setInputPaths(job, new Path(args[0]));
    		FileOutputFormat.setOutputPath(job, new Path(args[1]));
    		
    		// 7 将job中配置的相关参数,以及job所用的java类所在的jar包, 提交给yarn去运行
    		boolean result = job.waitForCompletion(true);
    		System.exit(result ? 0 : 1);
    	}
    }
    

3.6 WritableComparable排序案例实操(区内排序)

3.6.1 需求

要求每个省份手机号输出的文件中按照总流量内部排序。

3.6.2 需求分析

基于前一个需求,增加自定义分区类,分区按照省份手机号设置。

分区内排序案例分析

在这里插入图片描述

3.6.3 案例实操

  1. 添加自定义分区

    package com.bigdata.hadoop.mapreduce.sort;
    
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapred.JobConf;
    import org.apache.hadoop.mapred.Partitioner;
    
    import java.util.HashMap;
    
    /**
     * 根据手机号前三位分发不同的reduce程序,其输入结果是map的输出
     * @author dwjf321
     */
    public class ProvincePartitioner implements Partitioner<FlowBean, Text> {
          
          
    
        public static HashMap<String, Integer> provinceDict = new HashMap<String, Integer>();
        static{
          
          
            provinceDict.put("136", 0);
            provinceDict.put("137", 1);
            provinceDict.put("138", 2);
            provinceDict.put("139", 3);
        }
        @Override
        public int getPartition(FlowBean key, Text value, int partition) {
          
          
            //根据手机号的前三位分区
            String phoneNum = value.toString().substring(0,3);
            Integer partitionId = provinceDict.get(phoneNum);
            return partitionId == null ? 4 : partitionId;
        }
    
        @Override
        public void configure(JobConf jobConf) {
          
          
    
        }
    }
    
  2. 在驱动类中添加分区类

    // 加载自定义分区类
    job.setPartitionerClass(ProvincePartitioner.class);
    
    // 设置Reducetask个数
    job.setNumReduceTasks(5);
    

3.7 Combiner 合并

3.7.1 Combiner 合并

  1. Combiner 是 MR 程序中 Mapper 和 Reducer 之外的一种组件。

  2. Combiner 组件的父类就是 Reducer。

  3. Combiner 和 Reducer的区别在于运行的位置:

    Combiner 是在每个 MapTask 所在的节点运行。

    Reducer 是接收全局所有的 Maper 的输出结果。

  4. Combiner 的意义就是对每个 MapTask 的输出进行局部汇总,以减小网络传输量。

  5. Combiner 你能够应用的前提是不能影响最终的业务逻辑。而且,Combiner 的输出 KV 应该跟 Reducer 的输入 KV 类型要对应起来。

3.7.2 自定义 Combiner 实现步骤

自定义一个 Combiner 继承 Reducer,重写 Reduce 方法

public class WordcountCombiner extends Reducer<Text, IntWritable, Text, IntWritable>{
    
    
	
	IntWritable v = new IntWritable();
	
	@Override
	protected void reduce(Text key, Iterable<IntWritable> values,
			Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
    
    
		
		int sum = 0;
		
		// 1 汇总操作
		for (IntWritable value : values) {
    
    
			sum += value.get();
		}
		
		v.set(sum);
		
		// 2 写出
		context.write(key, v);
	}
}

在驱动中设置:

job.setCombinerClass(WordcountCombiner.class);

3.8 Combiner合并案例实操

3.8.1 需求

统计过程中对每一个 MapTask 的输出进行局部汇总,以减小网络传输量即采用 Combiner 功能。

输入数据:

banzhang ni hao
xihuan hadoop banzhang
banzhang ni hao
xihuan hadoop banzhang

期望输出数据:

期望:Combine输入数据多,输出时经过合并,输出数据降低。

3.8.2 需求分析

需求:对每个 MapTask 的输出局部汇总(Combiner)

在这里插入图片描述

3.8.3 案例实操-方案一

  1. 增加一个WordcountCombiner类继承Reducer

    package com.bigdata.hadoop.mapreduce.combiner;
    import java.io.IOException;
    import org.apache.hadoop.io.IntWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Reducer;
    
    public class WordcountCombiner extends Reducer<Text, IntWritable, Text, IntWritable>{
          
          
    
    IntWritable v = new IntWritable();
    
    	@Override
    	protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
          
          
    
            // 1 汇总
    		int sum = 0;
    
    		for(IntWritable value :values){
          
          
    			sum += value.get();
    		}
    
    		v.set(sum);
    
    		// 2 写出
    		context.write(key, v);
    	}
    }
    
  2. 在WordcountDriver驱动类中指定Combiner

    // 指定需要使用combiner,以及用哪个类作为combiner的逻辑
    job.setCombinerClass(WordcountCombiner.class);
    

3.8.4 案例实操-方案二

  1. WordcountReducer作为 Combiner 在 WordcountDriver驱动类中指定

    // 指定需要使用Combiner,以及用哪个类作为Combiner的逻辑
    job.setCombinerClass(WordcountReducer.class);
    
  2. 运行程序结果如图:
    在这里插入图片描述

    未使用前

在这里插入图片描述

使用后

3.9 GroupingComparator分组(辅助排序)

对 Reduce 阶段的数据根据某一个或几个字段进行分组。

分组排序步骤:

  1. 自定义类继承 WritableComparator

  2. 重写 compare()方法

    @Override
    public int compare(WritableComparable a, WritableComparable b) {
          
          
    		// 比较的业务逻辑
    		… …
    
    		return result;
    }
    
  3. 创建一个构造将比较对象的类传给父类

    protected OrderGroupingComparator() {
          
          
    		super(OrderBean.class, true);
    }
    

3.10 GroupingComparator分组案例实操

3.10.1 需求

有如下定的数据

订单数据
订单ID 商品ID 成交金额
0000001 Pdt_01 222.8
0000001 Pdt_02 33.8
0000002 Pdt_03 522.8
0000002 Pdt_04 122.4
0000002 Pdt_05 722.4
0000003 Pdt_06 232.8
0000003 Pdt_02 33.8

现在需要求出每一个订单中最贵的商品。

输入数据:

0000001	Pdt_01	222.8
0000002	Pdt_05	722.4
0000001	Pdt_02	33.8
0000003	Pdt_06	232.8
0000003	Pdt_02	33.8
0000002	Pdt_03	522.8
0000002	Pdt_04	122.4

期望输出数据:

1	222.8
2	722.4
3	232.8

3.10.2 需求分析

  1. 利用 “订单ID和成交金额” 作为 key,可以将 Map 阶段读到的所有定的数据按照 ID 升序排序,如果 ID 相同再按照金额降序排序,发送到 Reduce。

  2. 在 Reduce 端利用 groupingComparator 将 订单ID 相同的 KV 聚合成组,然后取第一个即是该订单中最贵的商品。

    需求:求每个订单中最贵的商品 (GroupingComparator )
    在这里插入图片描述

    过程分析

3.10.3 代码实现

  1. 定义订单信息 OrderBean 类

    package com.bigdata.hadoop.mapreduce.order;
    import java.io.DataInput;
    import java.io.DataOutput;
    import java.io.IOException;
    import org.apache.hadoop.io.WritableComparable;
    
    public class OrderBean implements WritableComparable<OrderBean> {
          
          
    
    	private int order_id; // 订单id号
    	private double price; // 价格
    
    	public OrderBean() {
          
          
    		super();
    	}
    
    	public OrderBean(int order_id, double price) {
          
          
    		super();
    		this.order_id = order_id;
    		this.price = price;
    	}
    
    	@Override
    	public void write(DataOutput out) throws IOException {
          
          
    		out.writeInt(order_id);
    		out.writeDouble(price);
    	}
    
    	@Override
    	public void readFields(DataInput in) throws IOException {
          
          
    		order_id = in.readInt();
    		price = in.readDouble();
    	}
    
    	@Override
    	public String toString() {
          
          
    		return order_id + "\t" + price;
    	}
    
    	public int getOrder_id() {
          
          
    		return order_id;
    	}
    
    	public void setOrder_id(int order_id) {
          
          
    		this.order_id = order_id;
    	}
    
    	public double getPrice() {
          
          
    		return price;
    	}
    
    	public void setPrice(double price) {
          
          
    		this.price = price;
    	}
    
    	// 二次排序
    	@Override
    	public int compareTo(OrderBean o) {
          
          
    
    		int result;
    
    		if (order_id > o.getOrder_id()) {
          
          
    			result = 1;
    		} else if (order_id < o.getOrder_id()) {
          
          
    			result = -1;
    		} else {
          
          
    			// 价格倒序排序
    			result = price > o.getPrice() ? -1 : 1;
    		}
    
    		return result;
    	}
    }
    
    1. 编写```OrderSortMapper``类

      package com.bigdata.hadoop.mapreduce.order;
      
      import java.io.IOException;
      import org.apache.hadoop.io.LongWritable;
      import org.apache.hadoop.io.NullWritable;
      import org.apache.hadoop.io.Text;
      import org.apache.hadoop.mapreduce.Mapper;
      
      public class OrderMapper extends Mapper<LongWritable, Text, OrderBean, NullWritable> {
              
              
      
      	OrderBean k = new OrderBean();
      	
      	@Override
      	protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
              
              
      		
      		// 1 获取一行
      		String line = value.toString();
      		
      		// 2 截取
      		String[] fields = line.split("\t");
      		
      		// 3 封装对象
      		k.setOrder_id(Integer.parseInt(fields[0]));
      		k.setPrice(Double.parseDouble(fields[2]));
      		
      		// 4 写出
      		context.write(k, NullWritable.get());
      	}
      }
      
      
    2. 编写OrderSortGroupingComparator

      package com.bigdata.hadoop.mapreduce.order;
      import org.apache.hadoop.io.WritableComparable;
      import org.apache.hadoop.io.WritableComparator;
      
      public class OrderGroupingComparator extends WritableComparator {
              
              
      
      	protected OrderGroupingComparator() {
              
              
      		super(OrderBean.class, true);
      	}
      
      	@Override
      	public int compare(WritableComparable a, WritableComparable b) {
              
              
      
      		OrderBean aBean = (OrderBean) a;
      		OrderBean bBean = (OrderBean) b;
      
      		int result;
      		if (aBean.getOrder_id() > bBean.getOrder_id()) {
              
              
      			result = 1;
      		} else if (aBean.getOrder_id() < bBean.getOrder_id()) {
              
              
      			result = -1;
      		} else {
              
              
      			result = 0;
      		}
      
      		return result;
      	}
      }
      
    3. 编写OrderSortReducer

      package com.bigdata.hadoop.mapreduce.order;
      
      import java.io.IOException;
      import org.apache.hadoop.io.NullWritable;
      import org.apache.hadoop.mapreduce.Reducer;
      
      public class OrderReducer extends Reducer<OrderBean, NullWritable, OrderBean, NullWritable> {
              
              
      
      	@Override
      	protected void reduce(OrderBean key, Iterable<NullWritable> values, Context context)		throws IOException, InterruptedException {
              
              
      		
      		context.write(key, NullWritable.get());
      	}
      }
      
    4. 编写OrderSortDriver

      package com.bigdata.hadoop.mapreduce.order;
      
      import java.io.IOException;
      import org.apache.hadoop.conf.Configuration;
      import org.apache.hadoop.fs.Path;
      import org.apache.hadoop.io.NullWritable;
      import org.apache.hadoop.mapreduce.Job;
      import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
      import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
      
      public class OrderDriver {
              
              
      
      	public static void main(String[] args) throws Exception, IOException {
              
              
      
      // 输入输出路径需要根据自己电脑上实际的输入输出路径设置
      		args  = new String[]{
              
              "e:/input/inputorder" , "e:/output1"};
      
      		// 1 获取配置信息
      		Configuration conf = new Configuration();
      		Job job = Job.getInstance(conf);
      
      		// 2 设置jar包加载路径
      		job.setJarByClass(OrderDriver.class);
      
      		// 3 加载map/reduce类
      		job.setMapperClass(OrderMapper.class);
      		job.setReducerClass(OrderReducer.class);
      
      		// 4 设置map输出数据key和value类型
      		job.setMapOutputKeyClass(OrderBean.class);
      		job.setMapOutputValueClass(NullWritable.class);
      
      		// 5 设置最终输出数据的key和value类型
      		job.setOutputKeyClass(OrderBean.class);
      		job.setOutputValueClass(NullWritable.class);
      
      		// 6 设置输入数据和输出数据路径
      		FileInputFormat.setInputPaths(job, new Path(args[0]));
      		FileOutputFormat.setOutputPath(job, new Path(args[1]));
      
      		// 8 设置reduce端的分组
      	job.setGroupingComparatorClass(OrderGroupingComparator.class);
      
      		// 7 提交
      		boolean result = job.waitForCompletion(true);
      		System.exit(result ? 0 : 1);
      	}
      }
      

4. MapTask 工作机制

4.1 MapTask 工作机制图解

MapTask 工作机制如图:

在这里插入图片描述

MapTask 工作机制
  1. Read 阶段:MapTask 通过用户编写的 RecodReader,从输入 InputSplit 中解析出一个个 key/value。
  2. Map 阶段:该阶段主要是将解析出的 key/value 交给用户编写 map() 函数处理,并产生一系列新的 key/value。
  3. Collect 收集阶段:在用户编写 map() 函数中,当数据处理完成后,一般会调用 OutputCollector.collect()输出结果。该函数内部,它将生成的 key/value 分区(调用 Partitioner),并写入一个环形缓冲区中。
  4. Spill 阶段:即 “溢写”,当环形缓冲区满后,MapReduce 会将数据写到本地磁盘上,生成一个临时文件。需要注意的是,将数据写入本地磁盘之前,先要对数据进行一次本地排序,并在必要时对数据进行合并、压缩等操作。
  5. Combine 阶段:当所有数据处理完成后,MapTask 对所有临时文件进行一次合并,以确保最终只生成一个数据文件。

当所有数据处理完后,MapTask 会将所有临时文件合并成一个大文件,并保存到文件 out/file.out中,同时生成相应的索引文件 output/file.out.index

在进行文件合并过程中,MapTask 以分区为单位进行合并。对于某个分区,它将采用多轮递归合并的方式。每轮合并 10 (io.sort.factor控制,默认10)个文件,并将产生的文件重新写入待核保列表中,对文件排序后,重复以上过程,直到最终得到一个大文件。

让每个 MapTask 最终只生成一个数据文件,可避免同时打开大量文件和同时读取大量小文件产生的随机读取带来的开销。

4.2 溢写阶段详情

  1. 利用快速排序算法对缓存区内的数据进行排序,排序方式是:先按照分区编号 Partition 进行排序,然后按照 key 进行排序。这样,经过排序后,数据以分区为单位聚集在一起,且同一分区内所有数据按照 key 有序。
  2. 按照分区编号有小到大一次将每个分区中的数据写入任务目录下的临时文件 output/spillN.out(N 表示当前一些次数) 中。如果用户设置了 Combiner,则写入文件之前,对每个分区中的数据进行一次聚集操作。
  3. 将分区数据的元信息写到内存索引数据结构 SpillRecord 中,其中每个分区的元信息包括:临时文件偏移量、压缩钱数据大小和压缩后数据大小。如果当前内存索引大小超过 1MB,则将内存索引写到文件 output/spillN.out.index中。

5. ReduceTask 工作机制

5.1 ReduceTask 工作机制图解

ReduceTask 工作机制如图所示:

在这里插入图片描述

ReduceTask 工作机制
  1. Copy 阶段:ReduceTask 从各个 MapTask 上远程拷贝一片数据,并针对谋篇数据,如果其大小超过一定阈值,则写入到磁盘,否则直接放到内存中。
  2. Merge 阶段:在远程拷贝数据的同事,ReduceTask 启动了两个后台线程对内存和磁盘上的文件进行合并,以防止内存使用过多活磁盘上文件过多。
  3. Sort 阶段:按照 MapReduce 语义,用户编写 reduce()函数输入数据是按 key 进行聚集的一组数据。为了将 key 相同的数据聚在一起,Hadoop 采用了基于排序的策略。由于各个 MapTask 已经实现对自己的处理结果进行了局部排序。因此,ReduceTask 只需对所有数据进行一次归并排序即可。
  4. Reduce 阶段reduce()函数将计算结果写到 HDFS 上。

5.2 设置 ReduceTask 并行度(个数)

ReduceTask 的并行度同样影响整个 Job 的执行并发度和执行效率,但与 MapTask 的并发数由切片数决定不同,ReduceTask 数量的决定是可以直接手动配置。

// 默认值是1,手动设置为4
job.setNumReduceTasks(4);

5.3 注意事项

  1. Reduce = 0,表示没有Reduce阶段,输出文件个数和 Map 个数一致。
  2. ReduceTask 默认值是 1,所以输出文件个数为一个。
  3. 如果数据分布不均匀,有可能在 Reduce 阶段产生数据倾斜。
  4. ReduceTask 数量并不是任意设置,还要考虑业务逻辑需求。有些情况下,需要计算全局汇总结果,就只能有 1 个 ReduceTask。
  5. 具体多少个 ReduceTask,需要根据集群性能而定。
  6. 如果分区数不是 1, 但是 ReduceTask 为 1,不会执行分区过程。因为在 MapT 的源码中,执行分区的前提是先判断 ReduceNum 个数是否大于1.不大于 1 肯定不执行分区过程。

6. OutputFormat 数据输出

6.1 OutputFormat 接口实现类

OutputFormat 是 MapReduce 输出的基类,所有实现 MapReduce 输出都实现了 OutputFormat 接口。下面我们介绍几种常见的 OutputFormat 实现类。

  1. 文本输出 TextOutputFormat

    默认的输出格式是 TextOutputFormat,它把每条记录写为文本行。它的键和值可以是任意类型,因为 TextOutputFormat调用toString()方法把他们转换为字符串。

sequenceDiagramFileOutputFormat```

mermaid sequenceDiagramFileOutputFormat输出作为后续 MapReudce 任务的输入,这便是一种好的输出格式。因为它的格式紧凑,很容易被压缩。

  1. 自定义 OutputFormat

    根据用户需求,自定义实现输出。

6.2 自定义 OutputFormat

6.2.1 使用场景

为了实现控制最终文件的输出路径和输出格式,可以自定义 OutputFormat。

例如:要在一个 MapReduce 程序中根据数据的不同输出两种类型结果到不同目录,这类灵活的输出需求可以通过自定义 OutputFormat 来实现。

6.2.2 自定义 OutputFormat 步骤

  1. 自定义一个类继承 FileOutputFormat
  2. 改写 RecordWriter,具体改写输出数据的方法 write()

6.3 自定义 OutputFormat 案例实操

6.3.1 需求

过滤输入的 log 日志,包含 amap 的网站输出到 amap.log,不包含的输出到 other.log。

输入数据:

http://www.baidu.com
http://www.google.com
http://cn.bing.com
http://www.amap.com
http://www.sohu.com
http://www.sina.com
http://www.sin2a.com
http://www.sin2desa.com
http://www.sindsafa.com

期望输出结果:

amap.log

http://www.amap.com

other.log

http://www.baidu.com
http://www.google.com
http://cn.bing.com
http://www.sohu.com
http://www.sina.com
http://www.sin2a.com
http://www.sin2desa.com
http://www.sindsafa.com

6.3.2 案例实操

  1. 编写 FilterMapper 类

    package com.bigdata.hadoop.mapreduce.outputformat;
    
    import org.apache.hadoop.io.LongWritable;
    import org.apache.hadoop.io.NullWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Mapper;
    
    import java.io.IOException;
    
    public class FilterMapper extends Mapper<LongWritable, Text, Text, NullWritable>{
          
          
    
        @Override
        protected void map(LongWritable key, Text value, Context context)	throws IOException, InterruptedException {
          
          
    
            // 写出
            context.write(value, NullWritable.get());
        }
    }
    
  2. 编写 FilterReducer 类

    package com.bigdata.hadoop.mapreduce.outputformat;
    
    import org.apache.hadoop.io.NullWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Reducer;
    
    import java.io.IOException;
    
    public class FilterReducer extends Reducer<Text, NullWritable, Text, NullWritable> {
          
          
    
        Text k = new Text();
    
        @Override
        protected void reduce(Text key, Iterable<NullWritable> values, Context context)		throws IOException, InterruptedException {
          
          
    
            // 1 获取一行
            String line = key.toString();
    
            // 2 拼接
            line = line + "\r\n";
    
            // 3 设置key
            k.set(line);
    
            // 4 输出
            context.write(k, NullWritable.get());
        }
    }
    
  3. 自定义一个 OutputFormat 类

    package com.bigdata.hadoop.mapreduce.outputformat;
    
    import org.apache.hadoop.io.NullWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.RecordWriter;
    import org.apache.hadoop.mapreduce.TaskAttemptContext;
    import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
    
    import java.io.IOException;
    
    public class FilterOutputFormat extends FileOutputFormat<Text, NullWritable>{
          
          
    
        @Override
        public RecordWriter<Text, NullWritable> getRecordWriter(TaskAttemptContext job)			throws IOException, InterruptedException {
          
          
    
            // 创建一个RecordWriter
            return new FilterRecordWriter(job);
        }
    }
    
  4. 编写 RecordWriter 类

    package com.bigdata.hadoop.mapreduce.outputformat;
    
    import org.apache.hadoop.fs.FSDataOutputStream;
    import org.apache.hadoop.fs.FileSystem;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.IOUtils;
    import org.apache.hadoop.io.NullWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.RecordWriter;
    import org.apache.hadoop.mapreduce.TaskAttemptContext;
    
    import java.io.IOException;
    
    public class FilterRecordWriter extends RecordWriter<Text, NullWritable> {
          
          
    
        FSDataOutputStream amapOut = null;
        FSDataOutputStream otherOut = null;
    
        public FilterRecordWriter(TaskAttemptContext job) {
          
          
    
            // 1 获取文件系统
            FileSystem fs;
    
            try {
          
          
                fs = FileSystem.get(job.getConfiguration());
    
                // 2 创建输出文件路径
                Path amapOutPath = new Path("/amap.log");
                Path otherPath = new Path("/other.log");
    
                // 3 创建输出流
                amapOut = fs.create(amapOutPath);
                otherOut = fs.create(otherPath);
            } catch (IOException e) {
          
          
                e.printStackTrace();
            }
        }
    
        @Override
        public void write(Text key, NullWritable value) throws IOException, InterruptedException {
          
          
    
            // 判断是否包含“amap”输出到不同文件
            if (key.toString().contains("amap")) {
          
          
                amapOut.write(key.toString().getBytes());
            } else {
          
          
                otherOut.write(key.toString().getBytes());
            }
        }
    
        @Override
        public void close(TaskAttemptContext context) throws IOException, InterruptedException {
          
          
    
            // 关闭资源
            IOUtils.closeStream(amapOut);
            IOUtils.closeStream(otherOut);
        }
    }
    
  5. 编写 FilterDriver 类

    package com.bigdata.hadoop.mapreduce.outputformat;
    
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.NullWritable;
    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;
    
    public class FilterDriver {
          
          
    
        public static void main(String[] args) throws Exception {
          
          
    
            // 输入输出路径需要根据自己电脑上实际的输入输出路径设置
            args = new String[] {
          
           "/input/inputoutputformat", "/output2" };
    
            Configuration conf = new Configuration();
            Job job = Job.getInstance(conf);
    
            job.setJarByClass(FilterDriver.class);
            job.setMapperClass(FilterMapper.class);
            job.setReducerClass(FilterReducer.class);
    
            job.setMapOutputKeyClass(Text.class);
            job.setMapOutputValueClass(NullWritable.class);
    
            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(NullWritable.class);
    
            // 要将自定义的输出格式组件设置到job中
            job.setOutputFormatClass(FilterOutputFormat.class);
    
            FileInputFormat.setInputPaths(job, new Path(args[0]));
    
            // 虽然我们自定义了outputformat,但是因为我们的outputformat继承自fileoutputformat
            // 而fileoutputformat要输出一个_SUCCESS文件,所以,在这还得指定一个输出目录
            FileOutputFormat.setOutputPath(job, new Path(args[1]));
    
            boolean result = job.waitForCompletion(true);
            System.exit(result ? 0 : 1);
        }
    }
    

7. Join 多种应用

7.1 Reduce Join 工作原理

  1. Map 端的主要工作:为来自不同表和文件的 key/value 对,打标签以区别不同来源的记录。然后用连接字段作为 key,其余部分和新加的标志作为 value,最后进行输出。
  2. Reuce 端的主要工作:在 Reduce 端以连接字段作为 key 的分组已经完成,我们只需要在每一个分组当中将那些来源于不同文件的记录(Map 阶段已经打标记)分开,最后进行合并就 ok 了。

7.2 Reduce Join 案例实操

7.2.1 需求

id pid amount
1001 01 1
1002 02 2
1003 03 3
1004 01 4
1005 02 5
1006 03 6
订单数据表t_order
pid pname
01 小米
02 华为
03 格力
商品信息表t_product

将商品信息表中数据根据商品pid合并到订单数据表中。

id pname amount
1001 小米 1
1004 小米 4
1002 华为 2
1005 华为 5
1003 格力 3
1006 格力 6
最终数据形式

7.2.2 需求分析

通过将关联条件作为 Map 输出的 key,将两表满足 Join 条件的数据并携带数据所来源的文件信息,发往同一个 ReduceTask ,在 Reduce 中进行数据的串联,如图所示:

在这里插入图片描述

Reduce 端表合并

7.2.3 代码实现

  1. 创建商品和订单合并后的实体类TableBean

    package com.bigdata.hadoop.mapreduce.table;
    
    import org.apache.hadoop.io.Writable;
    
    import java.io.DataInput;
    import java.io.DataOutput;
    import java.io.IOException;
    
    public class TableBean implements Writable {
          
          
        private String order_id; // 订单id
        private String p_id;      // 产品id
        private int amount;       // 产品数量
        private String pname;     // 产品名称
        private String flag;      // 表的标记
    
        public TableBean() {
          
          
            super();
        }
    
        public TableBean(String order_id, String p_id, int amount, String pname, String flag) {
          
          
    
            super();
    
            this.order_id = order_id;
            this.p_id = p_id;
            this.amount = amount;
            this.pname = pname;
            this.flag = flag;
        }
    
        public String getFlag() {
          
          
            return flag;
        }
    
        public void setFlag(String flag) {
          
          
            this.flag = flag;
        }
    
        public String getOrder_id() {
          
          
            return order_id;
        }
    
        public void setOrder_id(String order_id) {
          
          
            this.order_id = order_id;
        }
    
        public String getP_id() {
          
          
            return p_id;
        }
    
        public void setP_id(String p_id) {
          
          
            this.p_id = p_id;
        }
    
        public int getAmount() {
          
          
            return amount;
        }
    
        public void setAmount(int amount) {
          
          
            this.amount = amount;
        }
    
        public String getPname() {
          
          
            return pname;
        }
    
        public void setPname(String pname) {
          
          
            this.pname = pname;
        }
    
        @Override
        public void write(DataOutput out) throws IOException {
          
          
            out.writeUTF(order_id);
            out.writeUTF(p_id);
            out.writeInt(amount);
            out.writeUTF(pname);
            out.writeUTF(flag);
        }
    
        @Override
        public void readFields(DataInput in) throws IOException {
          
          
            this.order_id = in.readUTF();
            this.p_id = in.readUTF();
            this.amount = in.readInt();
            this.pname = in.readUTF();
            this.flag = in.readUTF();
        }
    
        @Override
        public String toString() {
          
          
            return order_id + "\t" + pname + "\t" + amount + "\t";
        }
    }
    
  2. 编写 TableMapper

    package com.bigdata.hadoop.mapreduce.table;
    
    import org.apache.hadoop.io.LongWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Mapper;
    import org.apache.hadoop.mapreduce.lib.input.FileSplit;
    
    import java.io.IOException;
    
    public class TableMapper extends Mapper<LongWritable, Text, Text, TableBean>{
          
          
    
        String name;
        TableBean bean = new TableBean();
        Text k = new Text();
    
        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
          
          
    
            // 1 获取输入文件切片
            FileSplit split = (FileSplit) context.getInputSplit();
    
            // 2 获取输入文件名称
            name = split.getPath().getName();
        }
    
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
          
          
    
            // 1 获取输入数据
            String line = value.toString();
    
            // 2 不同文件分别处理
            if (name.startsWith("order")) {
          
          // 订单表处理
    
                // 2.1 切割
                String[] fields = line.split("\t");
    
                // 2.2 封装bean对象
                bean.setOrder_id(fields[0]);
                bean.setP_id(fields[1]);
                bean.setAmount(Integer.parseInt(fields[2]));
                bean.setPname("");
                bean.setFlag("order");
    
                k.set(fields[1]);
            }else {
          
          // 产品表处理
    
                // 2.3 切割
                String[] fields = line.split("\t");
    
                // 2.4 封装bean对象
                bean.setP_id(fields[0]);
                bean.setPname(fields[1]);
                bean.setFlag("pd");
                bean.setAmount(0);
                bean.setOrder_id("");
    
                k.set(fields[0]);
            }
    
            // 3 写出
            context.write(k, bean);
        }
    }
    
  3. 编写 TableReducer

    package com.bigdata.hadoop.mapreduce.table;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import org.apache.commons.beanutils.BeanUtils;
    import org.apache.hadoop.io.NullWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Reducer;
    
    public class TableReducer extends Reducer<Text, TableBean, TableBean, NullWritable> {
          
          
    
        @Override
        protected void reduce(Text key, Iterable<TableBean> values, Context context)	throws IOException, InterruptedException {
          
          
    
            // 1准备存储订单的集合
            ArrayList<TableBean> orderBeans = new ArrayList<>();
    
    		// 2 准备bean对象
            TableBean pdBean = new TableBean();
    
            for (TableBean bean : values) {
          
          
    
                if ("order".equals(bean.getFlag())) {
          
          // 订单表
    
                    // 拷贝传递过来的每条订单数据到集合中
                    TableBean orderBean = new TableBean();
    
                    try {
          
          
                        BeanUtils.copyProperties(orderBean, bean);
                    } catch (Exception e) {
          
          
                        e.printStackTrace();
                    }
    
                    orderBeans.add(orderBean);
                } else {
          
          // 产品表
    
                    try {
          
          
                        // 拷贝传递过来的产品表到内存中
                        BeanUtils.copyProperties(pdBean, bean);
                    } catch (Exception e) {
          
          
                        e.printStackTrace();
                    }
                }
            }
    
            // 3 表的拼接
            for(TableBean bean:orderBeans){
          
          
    
                bean.setPname (pdBean.getPname());
    
                // 4 数据写出去
                context.write(bean, NullWritable.get());
            }
        }
    }
    
  4. 编写 TableDriver

    package com.bigdata.hadoop.mapreduce.table;
    
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.NullWritable;
    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;
    
    public class TableDriver {
          
          
    
        public static void main(String[] args) throws Exception {
          
          
    
            // 0 根据自己电脑路径重新配置
            args = new String[]{
          
          "/input/inputtable","/output1"};
    
            // 1 获取配置信息,或者job对象实例
            Configuration configuration = new Configuration();
            Job job = Job.getInstance(configuration);
    
            // 2 指定本程序的jar包所在的本地路径
            job.setJarByClass(TableDriver.class);
    
            // 3 指定本业务job要使用的Mapper/Reducer业务类
            job.setMapperClass(TableMapper.class);
            job.setReducerClass(TableReducer.class);
    
            // 4 指定Mapper输出数据的kv类型
            job.setMapOutputKeyClass(Text.class);
            job.setMapOutputValueClass(TableBean.class);
    
            // 5 指定最终输出的数据的kv类型
            job.setOutputKeyClass(TableBean.class);
            job.setOutputValueClass(NullWritable.class);
    
            // 6 指定job的输入原始文件所在目录
            FileInputFormat.setInputPaths(job, new Path(args[0]));
            FileOutputFormat.setOutputPath(job, new Path(args[1]));
    
            // 7 将job中配置的相关参数,以及job所用的java类所在的jar包, 提交给yarn去运行
            boolean result = job.waitForCompletion(true);
            System.exit(result ? 0 : 1);
        }
    }
    
  5. 测试

    运行程序查看结果

    1001	小米	1	
    1001	小米	1	
    1002	华为	2	
    1002	华为	2	
    1003	格力	3	
    1003	格力	3
    

7.3 Map Join

  1. 使用场景

    Map Join 适用于一张表十分小、一张表很大的场景。

  2. 优点

    思考:在Reduce端处理过多的表,非常容易产生数据倾斜。怎么办?

    在 Map 端缓存多张表,提前处理业务逻辑,这样增加 Map 端业务,减少 Reduce 端数据的压力,尽可能的减少数据倾斜。

  3. 具体办法:采用 DistributedCache

    • 在Mapper的 setup阶段,将文件读取到缓存集合中。

    • 在驱动函数中加载缓存。

      // 缓存普通文件到Task运行节点。
      job.addCacheFile(new URI("file://cache/pd.txt"));
      

7.4 Map Join 实操

7.4.1 需求

id pid amount
1001 01 1
1002 02 2
1003 03 3
1004 01 4
1005 02 5
1006 03 6
订单数据表 t_order
pid pname
01 小米
02 华为
03 格力
商品信息表 t_product

将商品信息表中数据根据商品pid合并到订单数据表中。

id pname amount
1001 小米 1
1004 小米 4
1002 华为 2
1005 华为 5
1003 格力 3
1006 格力 6
最终数据形式

7.4.2 需求分析

Map Join 适用于关联表中有小表的情形。

Map 端表合并案例分析(Distributedcache)

在这里插入图片描述

Map 端表合并

7.4.3 代码实现

  1. 先在驱动模块中添加缓存文件

    package com.bigdata.hadoop.mapreduce.cache;
    
    import java.net.URI;
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.NullWritable;
    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;
    
    public class DistributedCacheDriver {
          
          
    
        public static void main(String[] args) throws Exception {
          
          
    
            // 0 根据自己电脑路径重新配置
            args = new String[]{
          
          "/input/inputtable2", "/output1"};
    
            // 1 获取job信息
            Configuration configuration = new Configuration();
            Job job = Job.getInstance(configuration);
    
            // 2 设置加载jar包路径
            job.setJarByClass(DistributedCacheDriver.class);
    
            // 3 关联map
            job.setMapperClass(DistributedCacheMapper.class);
    
            // 4 设置最终输出数据类型
            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(NullWritable.class);
    
            // 5 设置输入输出路径
            FileInputFormat.setInputPaths(job, new Path(args[0]));
            FileOutputFormat.setOutputPath(job, new Path(args[1]));
    
            // 6 加载缓存数据
            job.addCacheFile(new URI("file:///input/inputcache/pd.txt"));
    
            // 7 Map端Join的逻辑不需要Reduce阶段,设置reduceTask数量为0
            job.setNumReduceTasks(0);
    
            // 8 提交
            boolean result = job.waitForCompletion(true);
            System.exit(result ? 0 : 1);
        }
    }
    
  2. 读取缓存的文件数据

    package com.bigdata.hadoop.mapreduce.cache;
    
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.URI;
    import java.util.HashMap;
    import java.util.Map;
    import org.apache.commons.lang.StringUtils;
    import org.apache.hadoop.io.LongWritable;
    import org.apache.hadoop.io.NullWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Mapper;
    
    public class DistributedCacheMapper extends Mapper<LongWritable, Text, Text, NullWritable>{
          
          
    
        Map<String, String> pdMap = new HashMap<>();
    
        @Override
        protected void setup(Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {
          
          
    
            // 1 获取缓存的文件
            URI[] cacheFiles = context.getCacheFiles();
            String path = cacheFiles[0].getPath();
    
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
    
            String line;
            while(StringUtils.isNotEmpty(line = reader.readLine())){
          
          
    
                // 2 切割
                String[] fields = line.split("\t");
    
                // 3 缓存数据到集合
                pdMap.put(fields[0], fields[1]);
            }
    
            // 4 关流
            reader.close();
        }
    
        Text k = new Text();
    
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
          
          
    
            // 1 获取一行
            String line = value.toString();
    
            // 2 截取
            String[] fields = line.split("\t");
    
            // 3 获取产品id
            String pId = fields[1];
    
            // 4 获取商品名称
            String pdName = pdMap.get(pId);
    
            // 5 拼接
            k.set(line + "\t"+ pdName);
    
            // 6 写出
            context.write(k, NullWritable.get());
        }
    }
    

8. MapReduce 总结

在编写 MapReduce 程序时,需要考虑如下几个方面:

8.1 输入数据接口 (InputFormat)

  1. 默认使用的实现类是:TextInputFormat
  2. TextInputFormat的功能逻辑是:一次读一行文本,然后将该行的起始偏移量作为 key,行内容作为 value 返回。
  3. KeyValueTextInputFormat每一行均为一条记录,被分隔符分割为 key 和 value。默认分隔符是 tab (\t)。
  4. NlineInputFormat按照指定的行数 N 来划分切片。
  5. CombineTextInputFormat可以把多个小文件合并成一个切片处理,提供处理效率。
  6. 用户还可以自定义 InputFormat

8.2 逻辑处理接口 (Mapper)

用户根据业务需求实现其中三个方法:map()setup()cleanup()

8.3 Partitioner 分区

  1. 默认实现 HashPartitioner,逻辑是根据 key 的哈希值 和 numReduces 来返回一个分区号:key.hashCode() & Inter.MAXVALUE % numReduces
  2. 如果业务上有特别的需求,可以自定义分区。

8.4 Comparable 排序

  1. 我们用自定义的对象作为 key 来输出时,就必须要实现 WritableComparable接口,重写其中的 compareTo()方法。
  2. 部分排序:对最终输出的每个文件进行内部排序。
  3. 全排序:对所有数据进行排序,通常只有一个 Reduce。
  4. 二次排序:排序的条件有两个。

8.5 Combiner 合并

Combiner 合并可以提高程序执行效率,减少 IO 传输。但是使用时必须不能影响原有的业务处理结果。

8.6 Reduce 端分组:GroupingComparator

在 Reduce 端对 key 进行分组。应用于:在接收的 key 为 bean对象时,想让一个活几个字段相同的 key 进入到同一个 reduce方法时,可以采用分组排序。

8.7 逻辑处理接口 (Reducer)

用户根据业务需求实现其中三个方法:reduce()setup()cleanup()

8.8 输出数据接口 (OutputFormat)

  1. 默认实现类是 TextOutputFormat,将每一个 KV 对,向目标文件输出一行。
  2. mermaid sequenceDiagramFileOutputFormat输出作为后续 MapReduce任务的输入,这便是一种好的输出格式,因为它的格式紧凑,很容易被压缩。
  3. 用户还可以自定义 OutputFormat

猜你喜欢

转载自blog.csdn.net/dwjf321/article/details/110197470
今日推荐