• 5Hadoop学习笔记2


    MapReduce

    MapReduce概述

    • MapReduce定义

      • MapReduce是一个分布式运算程序的编程框架,是用户开发“基于Hadoop的数据分析应用”的核心框架
      • MapReduce的核心功能是将用户编写的业务逻辑代码和自带默认组件整合成一个完整的分布式运算程序,并发运行在一个Hadoop集群上。
    • MapReduce优缺点

      • 优点
        • MapReduce易于编程:它简单的实现一些接口,就可以完成一个分布式程序
        • 良好的扩展性:可以通过简单的增加机器来扩展它的能力
        • 高容错性:其中一台机器挂了,它可以把上面的计算任务转移到另一个节点上运行,不至于这个任务运行失败
        • 适合PB级以上海量数据的离线处理
      • 缺点
        • 不擅长实时计算
        • 不擅长流式计算:MapReduce的输入数据都是静态的,不能动态变化
        • 不擅长DAG(有向无环图)计算
          • 多个应用程序存在依赖关系,后一个应用程序的输入为前一个的输出。在这种情况下,MapReduce并不是不能做,而是使用后,每个MapReduce作业的输出结果都会写入到磁盘,会造成大量的磁盘IO,导致性能非常低下
    • MapReduce核心思想

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

    • MapReduce进程

      • 一个完整的MapReduce程序在分布式运行时有三类实例进程:
        • MrAPPMaster:负责整个程序的过程调度即状态协调
        • MapTask:负责Map阶段的整个数据处理流程
        • ReduceTask:负责Reduce阶段的整个数据处理流程
    • 常用数据序列化类型

      • Java类型 Hadoop Writable类型
        Boolean BooleanWritable
        Byte ByteWritable
        Int IntWritable
        Float FloatWritable
        Long LongWritable
        Double DoubleWritable
        String Text
        Map MapWritable
        Array ArrayWritable
        Null NullWritable
    • MapReduce编程规范

      • Mapper阶段
        • 用户自定义的Mapper要继承自己的父类
        • Mapper的输入数据是KV对的形式(KV的类型可自定义)
        • Mapper中的业务逻辑写在map()方法中
        • Mapper的输出数据是KV对的形式(KV的类型可自定义)
        • map()方法(MapTask进程)对每一个<K, V>调用一次
      • Reducer阶段
        • 用户自定义Reducer要继承自己的父类
        • Reducer的输入数据类型对应Mapper的输出数据类型,也是KV
        • Reducer的业务逻辑编写在reduce()方法中国
        • ReduceTask进程对每一组相同的<K, V>组调用一次reduce()方法
      • Driver阶段
        • 相当于YARN集群的客户端,用于提交我们整个程序到YARN集群,提交的是封装了MapReduce程序相关运行参数的job对象
    • WordCount案例

      • 创建Maven工程

      • 在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
          
      • 编写Mapper类

        • package com.lotuslaw.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: lotuslaw
           * @version: V1.0
           * @package: com.lotuslaw.mapreduce.wordcount
           * @create: 2021-11-23 9:51
           * @description:
           */
          
          /**
           * 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> {
          
              private Text outK = new Text();
              private IntWritable outV = new IntWritable(1);
          
              @Override
              protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
                  // 获取一行
                  String line = value.toString();
          
                  // 切割
                  String[] words = line.split(" ");
          
                  // 循环写出
                  for (String word : words) {
                      // 封装outK
                      outK.set(word);
                      // 写出
                      context.write(outK, outV);
                  }
              }
          }
          
      • 编写Reducer类

        • package com.lotuslaw.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: lotuslaw
           * @version: V1.0
           * @package: com.lotuslaw.mapreduce.wordcount
           * @create: 2021-11-23 9:51
           * @description:
           */
          
          /**
           * 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> {
          
              private IntWritable outV = new IntWritable();
          
              @Override
              protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
                  int sum = 0;
                  // 累加
                  for (IntWritable value : values) {
                      sum += value.get();
                  }
                  outV.set(sum);
          
                  // 写出
                  context.write(key, outV);
              }
          }
          
      • 编写Driver类

        • package com.lotuslaw.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: lotuslaw
           * @version: V1.0
           * @package: com.lotuslaw.mapreduce.wordcount
           * @create: 2021-11-23 9:51
           * @description:
           */
          /*
          atguigu	2
          banzhang	1
          cls	2
          hadoop	1
          jiao	1
          ss	2
          xue	1
           */
          public class WordCountDriver {
              public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
          
                  // 获取job
                  Configuration conf = new Configuration();
                  Job job = Job.getInstance(conf);
          
                  // 设置jar包路径
                  job.setJarByClass(WordCountDriver.class);
          
                  // 关联mapper和reducer
                  job.setMapperClass(WordCountMapper.class);
                  job.setReducerClass(WordCountReducer.class);
          
                  // 设置map输出的kv类型
                  job.setMapOutputKeyClass(Text.class);
                  job.setMapOutputValueClass(IntWritable.class);
          
                  // 设置最终输出的kv类型
                  job.setMapOutputKeyClass(Text.class);
                  job.setOutputValueClass(IntWritable.class);
          
                  // 设置输入路径和输出路径
                  // mapreduce程序中,如果输出路径存在,则直接报错
                  FileInputFormat.setInputPaths(job, new Path("D:\\7-bigdata\\test_data\\input"));
                  FileOutputFormat.setOutputPath(job, new Path("D:\\7-bigdata\\test_data\\output"));
          
                  // 提交job
                  boolean result = job.waitForCompletion(true);
          
                  System.exit(result ? 0 : 1);
              }
          }
          
      • 本地测试

        • 需要先配置好HADOOP_HOME变量以及Windows运行依赖
      • 提交到集群测试

        • 用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>
            
        • 将程序打成jar包,并上传Hadoop集群

        • 启动集群

        • 执行

          • hadoop jar  wc.jar
             com.lotuslaw.mapreduce.wordcount.WordCountDriver /user/lotuslaw/input /user/lotuslaw/output
            

    Hadoop序列化

    • 序列化概述

      • 序列化就是把内存中的对象,转换成字节序列(或其他数据传输协议)以便于存储到磁盘(持久化)或网络传输
      • 反序列化就是将收到字节序列(或其他数据传输协议)或者是磁盘持久化数据,转换成内存中的对象
      • 一般来说,“活的”对象只生存在内存里,关机断电就没有了。而且“活的”对象只能由本地的进程使用,不能被发送到网络上的另外一台计算机。然而序列化可以存储“活的”对象,可以将“活的”对象发送到远程计算机
      • 为什么不用Java的序列化
        • Java的序列化是一个重量级序列化框架(Serializable),一个对象被序列化后,会附带很多额外的信息(各种校验信息,Header,继承体系等),不便于在网络中高效传输。所以,Hadoop自己开发了一套序列化机制(Writable)
      • 序列化特点
        • 紧凑:高效使用存储空间
        • 快速:读写数据的额外开销小
        • 互操作:支持多语言的交互
    • 自定义bean对象实现序列化接口(Writable)

      • 具体实现bean对象序列化7步:

        • 必须实现Writable接口

        • 反序列化时,需要反射调用空参构造函数,所以必须由空参构造

          • public FlowBean() {
            	super();
            }
            
        • 重写序列化方法

          • @Override
            public void write(DataOutput out) throws IOException {
            	out.writeLong(upFlow);
            	out.writeLong(downFlow);
            	out.writeLong(sumFlow);
            }
            
        • 重写反序列化方法

          • @Override
            public void readFields(DataInput in) throws IOException {
            	upFlow = in.readLong();
            	downFlow = in.readLong();
            	sumFlow = in.readLong();
            }
            
        • 注意反序列化的顺序和序列化的顺序完全一致

        • 要想把结果显示在文件中,需要重写toString()方法,可以用"\t"分开,方便后续用

        • 如果需要将自定义的bean放在key中传输,则还需要实现Comparable接口,因为MapReduce框架中的Shuffle过程要求对key必须能排序。

          • @Override
            public int compareTo(FlowBean o) {
            	// 倒序排列,从大到小
            	return this.sumFlow > o.getSumFlow() ? -1 : 1;
            }
            
    • 序列化案例实操

      • 编写流量统计的Bean对象

        • package com.lotuslaw.mapreduce.writable;
          
          /**
           * @author: lotuslaw
           * @version: V1.0
           * @package: com.lotuslaw.mapreduce.writable
           * @create: 2021-11-23 11:10
           * @description:
           */
          
          import org.apache.hadoop.io.Writable;
          
          import java.io.DataInput;
          import java.io.DataOutput;
          import java.io.IOException;
          
          /**
           * 1.定义类实现writable接口
           * 2.重写序列化和反序列化方法
           * 3.重写空参构造
           * 4.toSting()方法
           */
          public class FlowBean implements Writable {
          
              private long upFlow;
              private long downFlow;
              private long sumFlow;
          
              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;
              }
              public void setSumFlow() {
                  this.sumFlow = this.upFlow + this.downFlow;
              }
          
              // 空参构造
              public FlowBean() {
              }
          
              @Override
              public void write(DataOutput dataOutput) throws IOException {
                  dataOutput.writeLong(upFlow);
                  dataOutput.writeLong(downFlow);
                  dataOutput.writeLong(sumFlow);
              }
          
              @Override
              public void readFields(DataInput dataInput) throws IOException {
                  this.upFlow = dataInput.readLong();
                  this.downFlow = dataInput.readLong();
                  this.sumFlow = dataInput.readLong();
              }
          
              @Override
              public String toString() {
                  return upFlow + "\t" + downFlow + "\t" + sumFlow;
              }
          }
          
      • 编写Mapper类

        • package com.lotuslaw.mapreduce.writable;
          
          import org.apache.hadoop.io.LongWritable;
          import org.apache.hadoop.io.Text;
          import org.apache.hadoop.mapreduce.Mapper;
          
          import java.io.IOException;
          
          /**
           * @author: lotuslaw
           * @version: V1.0
           * @package: com.lotuslaw.mapreduce.writable
           * @create: 2021-11-23 11:19
           * @description:
           */
          public class FlowMapper extends Mapper<LongWritable, Text, Text, FlowBean> {
          
              private Text outK = new Text();
              private FlowBean outV = new FlowBean();
          
              @Override
              protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
                  // 获取一行
                  String line = value.toString();
          
                  // 切割
                  String[] split = line.split("\t");
          
                  // 抓取想要的数据
                  // 手机号、上行流量、下行流量
                  String phone = split[1];
                  String up = split[split.length - 3];
                  String down = split[split.length - 2];
          
                  // 封装
                  outK.set(phone);
                  outV.setUpFlow(Long.parseLong(up));
                  outV.setDownFlow(Long.parseLong(down));
                  outV.setSumFlow();
          
                  // 写出
                  context.write(outK, outV);
              }
          }
          
      • 编写Reducer类

        • package com.lotuslaw.mapreduce.writable;
          
          import org.apache.hadoop.io.Text;
          import org.apache.hadoop.mapreduce.Reducer;
          
          import java.io.IOException;
          
          /**
           * @author: lotuslaw
           * @version: V1.0
           * @package: com.lotuslaw.mapreduce.writable
           * @create: 2021-11-23 11:26
           * @description:
           */
          public class FlowReducer extends Reducer<Text, FlowBean, Text, FlowBean> {
          
              private FlowBean outV = new FlowBean();
          
              @Override
              protected void reduce(Text key, Iterable<FlowBean> values, Context context) throws IOException, InterruptedException {
          
                  // 遍历集合累加值
                  long totalUp = 0;
                  long totalDown = 0;
                  for (FlowBean value : values) {
                      totalUp += value.getUpFlow();
                      totalDown += value.getDownFlow();
                  }
          
                  // 封装outK,outV
                  outV.setUpFlow(totalUp);
                  outV.setDownFlow(totalDown);
                  outV.setSumFlow();
          
                  // 写出
                  context.write(key, outV);
              }
          }
          
      • 编写Driver驱动类

        • package com.lotuslaw.mapreduce.writable;
          
          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;
          
          import java.io.IOException;
          
          /**
           * @author: lotuslaw
           * @version: V1.0
           * @package: com.lotuslaw.mapreduce.writable
           * @create: 2021-11-23 11:31
           * @description:
           */
          public class FlowDriver {
              public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
          
                  // 1.获取job
                  Configuration conf = new Configuration();
                  Job job = Job.getInstance(conf);
          
                  // 2.设置jar
                  job.setJarByClass(FlowDriver.class);
          
                  // 3.关联mapper、reducer
                  job.setMapperClass(FlowMapper.class);
                  job.setReducerClass(FlowReducer.class);
          
                  // 4.设置mapper输出key和value类型
                  job.setMapOutputKeyClass(Text.class);
                  job.setMapOutputValueClass(FlowBean.class);
          
                  // 5.设置最终输出的key和value类型
                  job.setOutputKeyClass(Text.class);
                  job.setOutputValueClass(FlowBean.class);
          
                  // 6.设置数据的输入路径和输出路径
                  FileInputFormat.setInputPaths(job, new Path("D:\\7-bigdata\\test_data\\input2"));
                  FileOutputFormat.setOutputPath(job, new Path("D:\\7-bigdata\\test_data\\output9"));
          
                  // 7.提交job
                  boolean result = job.waitForCompletion(true);
                  System.exit(result ? 0 : 1);
              }
          }
          

    MapReduce框架原理

    • InputFormat数据输入

      • 切片与MapTask并行度决定机制
        • MapTask的并行度决定Map阶段的任务处理并发度,进而影响到整个Job的处理速度
        • 数据块:Block是HDFS物理上把数据分成一块一块。数据块是HDFS存储数据单位
        • 数据切片:数据切片只是在逻辑上对输入进行分片,并不会在磁盘上将其切分成片进行存储。数据切片是MapReduce程序计算输入数据的单位,一个切片会对应启动一个MapTask

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

        • // 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());
          
        • FileInputFormat切片源码解析

      • FileInputFormat切片机制

        • 简单地按照文件的内容长度进行切片
        • 切片大小,默认等于Block大小
        • 切片时不考虑数据集整体,而是逐个针对每一个文件单独切片
      • TextInputFormat

        • FileInputFormat实现类

          • FileInputFormat常见的接口实现类包括:TextInputFormat、KeyValueTextInputFormat、NLineInputFormat、CombineTextInputFormat和自定义InputFormat等
        • TextInputFormat是默认的FileInputFormat实现类。按行读取每条记录。键是存储该行在整个文件中的起始字节偏移量, LongWritable类型。值是这行的内容,不包括任何行终止符(换行符和回车符),Text类型

          • // Rich learning form
            // Intelligent learning engine
            // Learning more convenient
            // From the real demand for more close to the enterprise
            
            (0,Rich learning form)
            (20,Intelligent learning engine)
            (49,Learning more convenient)
            (74,From the real demand for more close to the enterprise)
            
      • CombineTextInputFormat切片机制

        • 框架默认的TextInputFormat切片机制是对任务按文件规划切片,不管文件多小,都会是一个单独的切片,都会交给一个MapTask,这样如果有大量小文件,就会产生大量的MapTask,处理效率极其低下
        • 应用场景
          • CombineTextInputFormat用于小文件过多的场景,它可以将多个小文件从逻辑上规划到一个切片中,这样,多个小文件就可以交给一个MapTask处理
        • 虚拟存储切片最大值设置
          • CombineTextInputFormat.setMaxInputSplitSize(job, 4194304);// 4m
          • 注意:虚拟存储切片最大值设置最好根据实际的小文件大小情况来设置具体的值
        • 切片机制
          • 生成切片过程包括:虚拟存储过程和切片过程两部分
      • CombinTextInputFormat案例

        • 驱动类设置

          • // 设置InputFormat
            job.setInputFormatClass(CombineTextInputFormat.class);
            // 虚拟存储切片最大值设置20M
            CombineTextInputFormat.setMaxInputSplitSize(job, 20971520);
            
    • MapReduce工作流程

      • Shuffle工程从上述第7步开始到16步结束,如下:

        • MapTask手机我们的map()方法输出的KV对,放到内存缓冲区中

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

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

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

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

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

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

        • (1)Shuffle中的缓冲区大小会影响到MapReduce程序的执行效率,原则上说,缓冲区越大,磁盘io的次数越少,执行速度就越快。
          (2)缓冲区的大小可以通过参数调整,参数:mapreduce.task.io.sort.mb默认100M。
          
    • Shuffle机制

      • Map方法之后,Reduce方法之前的数据处理过程称之为Shuffle

      • Partition分区

        • 要求将统计结果按照条件输出到不同文件中

        • 默认Partitioner分区

        • 自定义Partitioner步骤

        • 分区总结

          • 如果ReduceTask的数量>getPartition的结果数,则会多产生几个空的输出文件part-r-000xx
          • 如果1<ReduceTask的数量<getPartition的结果数,则有一部分分区数据无处安放,会Exception
          • 如果ReduceTask的数量=1,则不管MapTask端输出多少个分区文件,最终结果都交给这一个ReduceTask,最终也就只会产生一个结果文件part-r-00000
          • 分区号必须从零开始,逐一累加
      • Partition分区案例实操

        • 在前述基础上增加一个分区类

          • package com.lotuslaw.mapreduce.partitioner2;
            
            import org.apache.hadoop.io.Text;
            import org.apache.hadoop.mapreduce.Partitioner;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.wordcount2
             * @create: 2021-11-23 14:03
             * @description:
             */
            public class ProvincePartitioner extends Partitioner<Text, FlowBean>{
                @Override
                public int getPartition(Text text, FlowBean flowBean, int i) {
                    // text是手机号
            
                    String phone = text.toString();
            
                    String prephone = phone.substring(0, 3);
            
                    int partition;
                    if ("136".equals(prephone)){
                        partition = 0;
                    }else if ("137".equals(prephone)){
                        partition = 1;
                    }else if ("138".equals(prephone)){
                        partition = 2;
                    }else if ("139".equals(prephone)){
                        partition = 3;
                    }else {
                        partition = 4;
                    }
                    return partition;
                }
            }
            
        • 在驱动函数中增加自定义数据分区设置和ReduceTask设置

          • // 指定自定义分区器
            job.setPartitionerClass(ProvincePartitioner.class);
            // 同时指定相应数量的ReduceTask
            job.setNumReduceTasks(5);
            
      • WritableComparable排序

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

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

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

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

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

        • 排序分类

          • 部分排序
            • MapReduce根据输入记录的键对数据集排序,保证输出的每个文件内部有序
          • 全排序
            • 最终输出结果只有一个文件,且文件内部有序。实现方式是只设置一个ReduceTask。但该方法在处理大型文件时效率极低,因为一台机器处理所有文件,完全丧失了MapReduce所提供的并行架构
          • 辅助排序(GroupinpComparator分组)
            • 在Reduce端对key进行分组。应用于:在接收的key为bean对象时,想让一个或几个字段相同(全部字段比较不相同)的key进入到同一个reduce方法时,可以采用分组排序
          • 二次排序
            • 在自定义排序过程中,如果compareTo中的判断条件为两个及以上,即为二次排序
        • 自定义排序WritableComparable

          • 原理分析

            • // bean对象作为Key传输,需要实现WritableComparable接口重写compareTo方法,就可以实现排序
              @Override
              public int compareTo(FlowBean bean) {
              
              	int result;
              		
              	// 按照总流量大小,倒序排列
              	if (this.sumFlow > bean.getSumFlow()) {
              		result = -1;
              	}else if (this.sumFlow < bean.getSumFlow()) {
              		result = 1;
              	}else {
              		result = 0;
              	}
              
              	return result;
              }
              
            • FlowBean对象

              • package com.lotuslaw.mapreduce.writableComparable;
                
                /**
                 * @author: lotuslaw
                 * @version: V1.0
                 * @package: com.lotuslaw.mapreduce.writable
                 * @create: 2021-11-23 11:10
                 * @description:
                 */
                
                import org.apache.hadoop.io.Writable;
                import org.apache.hadoop.io.WritableComparable;
                
                import java.io.DataInput;
                import java.io.DataOutput;
                import java.io.IOException;
                
                /**
                 * 1.定义类实现writable接口
                 * 2.重写序列化和反序列化方法
                 * 3.重写空参构造
                 * 4.toSting()方法
                 */
                public class FlowBean implements WritableComparable<FlowBean > {
                
                    private long upFlow;
                    private long 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;
                    }
                    public void setSumFlow() {
                        this.sumFlow = this.upFlow + this.downFlow;
                    }
                
                    private long sumFlow;
                
                    // 空参构造
                    public FlowBean() {
                    }
                
                    @Override
                    public void write(DataOutput dataOutput) throws IOException {
                        dataOutput.writeLong(upFlow);
                        dataOutput.writeLong(downFlow);
                        dataOutput.writeLong(sumFlow);
                    }
                
                    @Override
                    public void readFields(DataInput dataInput) throws IOException {
                        this.upFlow = dataInput.readLong();
                        this.downFlow = dataInput.readLong();
                        this.sumFlow = dataInput.readLong();
                    }
                
                    @Override
                    public String toString() {
                        return upFlow + "\t" + downFlow + "\t" + sumFlow;
                    }
                
                    @Override
                    public int compareTo(FlowBean o) {
                
                        // 总流量的倒序排序
                        if (this.sumFlow > o.sumFlow){
                            return -1;
                        }else if (this.sumFlow < o.sumFlow){
                            return 1;
                        }else {
                            // 按照上行流量的正序排
                            if (this.upFlow > o.upFlow){
                                return 1;
                            } else if (this.upFlow < o.upFlow){
                                return -1;
                            }else {
                                // 按照下行流量排,原理相同
                                return 0;
                            }
                        }
                    }
                }
                
            • Mapper类

              • package com.lotuslaw.mapreduce.writableComparable;
                
                import org.apache.hadoop.io.LongWritable;
                import org.apache.hadoop.io.Text;
                import org.apache.hadoop.mapreduce.Mapper;
                
                import java.io.IOException;
                
                /**
                 * @author: lotuslaw
                 * @version: V1.0
                 * @package: com.lotuslaw.mapreduce.writable
                 * @create: 2021-11-23 11:19
                 * @description:
                 */
                public class FlowMapper extends Mapper<LongWritable, Text, FlowBean, Text> {
                
                    private FlowBean outK = new FlowBean();
                    private Text outV = new Text();
                
                    @Override
                    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
                        // 获取一行
                        String line = value.toString();
                
                        // 切割
                        String [] split = line.split("\t");
                
                        // 封装
                        outV.set(split[0]);
                        outK.setUpFlow(Long.parseLong(split[1]));
                        outK.setDownFlow((Long.parseLong(split[2])));
                        outK.setSumFlow();
                
                        // 写出
                        context.write(outK, outV);
                    }
                }
                
            • Reducer类

              • package com.lotuslaw.mapreduce.writableComparable;
                
                import org.apache.hadoop.io.Text;
                import org.apache.hadoop.mapreduce.Reducer;
                
                import java.io.IOException;
                
                /**
                 * @author: lotuslaw
                 * @version: V1.0
                 * @package: com.lotuslaw.mapreduce.writable
                 * @create: 2021-11-23 11:26
                 * @description:
                 */
                public class FlowReducer 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);
                        }
                    }
                }
                
            • Driver类

              • package com.lotuslaw.mapreduce.writableComparable;
                
                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;
                
                import java.io.IOException;
                
                /**
                 * @author: lotuslaw
                 * @version: V1.0
                 * @package: com.lotuslaw.mapreduce.writable
                 * @create: 2021-11-23 11:31
                 * @description:
                 */
                public class FlowDriver {
                    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
                
                        // 1.获取job
                        Configuration conf = new Configuration();
                        Job job = Job.getInstance(conf);
                
                        // 2.设置jar
                        job.setJarByClass(FlowDriver.class);
                
                        // 3.关联mapper、reducer
                        job.setMapperClass(FlowMapper.class);
                        job.setReducerClass(FlowReducer.class);
                
                        // 4.设置mapper输出key和value类型
                        job.setMapOutputKeyClass(FlowBean.class);
                        job.setMapOutputValueClass(Text.class);
                
                        // 5.设置最终输出的key和value类型
                        job.setOutputKeyClass(Text.class);
                        job.setOutputValueClass(FlowBean.class);
                
                        // 6.设置数据的输入路径和输出路径
                        FileInputFormat.setInputPaths(job, new Path("D:\\7-bigdata\\test_data\\output9"));
                        FileOutputFormat.setOutputPath(job, new Path("D:\\7-bigdata\\test_data\\output11"));
                
                        // 7.提交job
                        boolean result = job.waitForCompletion(true);
                        System.exit(result ? 0 : 1);
                    }
                }
                
      • 分区内排序

        • 增加自定义分区类

          • package com.lotuslaw.mapreduce.partitionerandwritableComparable;
            
            import org.apache.hadoop.io.Text;
            import org.apache.hadoop.mapreduce.Partitioner;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.partitionerandwritableComparable
             * @create: 2021-11-23 15:25
             * @description:
             */
            public class ProvincePartitioner2 extends Partitioner<FlowBean, Text> {
                @Override
                public int getPartition(FlowBean flowBean, Text text, int i) {
            
                    String phone = text.toString();
            
                    String prePhone = phone.substring(0, 3);
            
                    int partition;
                    if ("136".equals(prePhone)){
                        partition =  0;
                    }else if("137".equals(prePhone)){
                        partition = 1;
                    }else if("138".equals(prePhone)){
                        partition = 2;
                    }else if("139".equals(prePhone)){
                        partition = 3;
                    }else {
                        partition = 4;
                    }
            
                    return partition;
                }
            }
            
            
        • 在驱动类中添加分区类

          • // 设置自定义分区器
            job.setPartitionerClass(ProvincePartitioner2.class);
            
            // 设置对应的ReduceTask的个数
            job.setNumReduceTasks(5);
            
      • Combiner合并

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

        • Combiner组件的父类就是Reducer

        • Combiner和Reducer的区别在于运行的位置:Combiner是在每一个MapTask所在的节点运行,Reducer是接收全局所有的Mapper的输出结果

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

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

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

          • package com.lotuslaw.mapreduce.combiner;
            
            import org.apache.hadoop.io.IntWritable;
            import org.apache.hadoop.io.Text;
            import org.apache.hadoop.mapreduce.Reducer;
            
            import java.io.IOException;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.combiner
             * @create: 2021-11-23 15:38
             * @description:
             */
            public class WordCountCombiner extends Reducer<Text, IntWritable, Text, IntWritable> {
            
                private IntWritable outV = new IntWritable();
            
                @Override
                protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
                    int sum = 0;
                    for (IntWritable value : values) {
                        sum += value.get();
                    }
                    outV.set(sum);
            
                    context.write(key, outV);
                }
            }
            
        • 在Job驱动类中设置

          • job.setCombinerClass(WordCountCombiner.class);
            
      • Combiner合并案例实操

        • 在Driver驱动类中指定Combiner

          • // 指定需要使用combiner,以及用哪个类作为combiner的逻辑
            job.setCombinerClass(WordCountCombiner.class);
            
        • 将Reducer作为Combiner在Driver驱动类中自定

          • // 指定需要使用Combiner,以及用哪个类作为Combiner的逻辑
            job.setCombinerClass(WordCountReducer.class);
            
    • OutputFormat数据输出

        • LogMapper

          • package com.lotuslaw.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;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.outputformat
             * @create: 2021-11-23 15:54
             * @description:
             */
            public class LogMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
                @Override
                protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            
                    // Map阶段不做任何处理
                    context.write(value, NullWritable.get());
                }
            }
            
        • LogReducer

          • package com.lotuslaw.mapreduce.outputformat;
            
            import org.apache.hadoop.io.NullWritable;
            import org.apache.hadoop.io.Text;
            import org.apache.hadoop.mapreduce.Reducer;
            
            import java.io.IOException;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.outputformat
             * @create: 2021-11-23 15:56
             * @description:
             */
            public class LogReducer extends Reducer<Text, NullWritable, Text, NullWritable> {
                @Override
                protected void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
                    // 防止相同数据丢失
                    for (NullWritable value : values) {
                        context.write(key, NullWritable.get());
                    }
                }
            }
            
        • 自定义一个LogOutputFormat

          • package com.lotuslaw.mapreduce.outputformat;
            
            import org.apache.hadoop.io.NullWritable;
            import org.apache.hadoop.io.Text;
            import org.apache.hadoop.mapreduce.OutputFormat;
            import org.apache.hadoop.mapreduce.RecordWriter;
            import org.apache.hadoop.mapreduce.TaskAttemptContext;
            import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
            
            import java.io.IOException;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.outputformat
             * @create: 2021-11-23 15:58
             * @description:
             */
            public class LogOutputFormat extends FileOutputFormat<Text, NullWritable> {
                @Override
                public RecordWriter<Text, NullWritable> getRecordWriter(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
            
                    LogRecordWriter lrw = new LogRecordWriter(taskAttemptContext);
            
                    return lrw;
                }
            }
            
        • LogRecordWriter

          • package com.lotuslaw.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;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.outputformat
             * @create: 2021-11-23 15:59
             * @description:
             */
            public class LogRecordWriter extends RecordWriter<Text, NullWritable> {
            
                private FSDataOutputStream atguiguOut;
                private FSDataOutputStream otherOut;
            
                public LogRecordWriter(TaskAttemptContext taskAttemptContext) {
                    // 创建两条流
                    try {
                        FileSystem fs = FileSystem.get(taskAttemptContext.getConfiguration());
                        atguiguOut = fs.create(new Path("D:\\7-bigdata\\test_data\\output7\\atguigu.log"));
                        otherOut = fs.create(new Path("D:\\7-bigdata\\test_data\\output7\\other.log"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            
                @Override
                public void write(Text text, NullWritable nullWritable) throws IOException, InterruptedException {
                    String log = text.toString();
                    // 具体写
                    if (log.contains("atguigu")){
                        atguiguOut.writeBytes(log + "\n");
                    }else {
                        otherOut.writeBytes(log + "\n");
                    }
            
                }
            
                @Override
                public void close(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
                    // 关流
                    IOUtils.closeStream(atguiguOut);
                    IOUtils.closeStream(otherOut);
                }
            }
            
        • LogDriver

          • package com.lotuslaw.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;
            
            import java.io.IOException;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.outputformat
             * @create: 2021-11-23 16:21
             * @description:
             */
            public class LogDriver {
                public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException, IOException {
            
                    Configuration conf = new Configuration();
                    Job job = Job.getInstance(conf);
            
                    job.setJarByClass(LogDriver.class);
                    job.setMapperClass(LogMapper.class);
                    job.setReducerClass(LogReducer.class);
            
                    job.setMapOutputKeyClass(Text.class);
                    job.setMapOutputValueClass(NullWritable.class);
            
                    job.setOutputKeyClass(Text.class);
                    job.setOutputValueClass(NullWritable.class);
            
                    //设置自定义的outputformat
                    job.setOutputFormatClass(LogOutputFormat.class);
            
                    FileInputFormat.setInputPaths(job, new Path("D:\\7-bigdata\\test_data\\input4"));
                    //虽然我们自定义了outputformat,但是因为我们的outputformat继承自fileoutputformat
                    //而fileoutputformat要输出一个_SUCCESS文件,所以在这还得指定一个输出目录
                    FileOutputFormat.setOutputPath(job, new Path("D:\\7-bigdata\\test_data\\output8"));
            
                    boolean b = job.waitForCompletion(true);
                    System.exit(b ? 0 : 1);
                }
            }
            
    • MapReduce内核源码解析

      • MapTask工作机制

        • (1)Read阶段:MapTask通过InputFormat获得的RecordReader,从输入InputSplit中解析出一个个key/value。
          (2)Map阶段:该节点主要是将解析出的key/value交给用户编写map()函数处理,并产生一系列新的key/value。
          (3)Collect收集阶段:在用户编写map()函数中,当数据处理完成后,一般会调用OutputCollector.collect()输出结果。在该函数内部,它会将生成的key/value分区(调用Partitioner),并写入一个环形内存缓冲区中。
          (4)Spill阶段:即“溢写”,当环形缓冲区满后,MapReduce会将数据写到本地磁盘上,生成一个临时文件。需要注意的是,将数据写入本地磁盘之前,先要对数据进行一次本地排序,并在必要时对数据进行合并、压缩等操作。
          溢写阶段详情:
          步骤1:利用快速排序算法对缓存区内的数据进行排序,排序方式是,先按照分区编号Partition进行排序,然后按照key进行排序。这样,经过排序后,数据以分区为单位聚集在一起,且同一分区内所有数据按照key有序。
          步骤2:按照分区编号由小到大依次将每个分区中的数据写入任务工作目录下的临时文件output/spillN.out(N表示当前溢写次数)中。如果用户设置了Combiner,则写入文件之前,对每个分区中的数据进行一次聚集操作。
          步骤3:将分区数据的元信息写到内存索引数据结构SpillRecord中,其中每个分区的元信息包括在临时文件中的偏移量、压缩前数据大小和压缩后数据大小。如果当前内存索引大小超过1MB,则将内存索引写到文件output/spillN.out.index中。
          (5)Merge阶段:当所有数据处理完成后,MapTask对所有临时文件进行一次合并,以确保最终只会生成一个数据文件。
          当所有数据处理完后,MapTask会将所有临时文件合并成一个大文件,并保存到文件output/file.out中,同时生成相应的索引文件output/file.out.index。
          在进行文件合并过程中,MapTask以分区为单位进行合并。对于某个分区,它将采用多轮递归合并的方式。每轮合并mapreduce.task.io.sort.factor(默认10)个文件,并将产生的文件重新加入待合并列表中,对文件排序后,重复以上过程,直到最终得到一个大文件。
          让每个MapTask最终只生成一个数据文件,可避免同时打开大量文件和同时读取大量小文件产生的随机读取带来的开销。
          
      • ReduceTask工作机制

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

      • Reduce Join

        • Map端的主要工作:为来自不同表或文件的key/value对,打标签以区别不同来源的记录。然后用连接字段作为key,其余部分和新加标志作为value,最后进行输出

        • Reduce端的主要工作:在Reduce端以连接字段作为key的分组已经完成,我们只需要在每一个分组当中将那些来源于不同文件的记录(在Map阶段已经打标志)分开,最后进行合并就ok了

        • 缺点:这种方式中,合并的操作是在Reduce阶段完成,Reduce端的处理压力太大,Map节点的运算负载则很低,资源利用率不高,且在Reduce阶段极易产生数据倾斜

        • 创建商品和订单合并后的TableBean类

          • package com.lotuslaw.mapreduce.reducejoin;
            
            import org.apache.hadoop.io.Writable;
            
            import java.io.DataInput;
            import java.io.DataOutput;
            import java.io.IOException;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.reducejoin
             * @create: 2021-11-23 18:15
             * @description:
             */
            public class TableBean implements Writable {
            
                private String id;
                private String pid;
                private int amount;
                private String pname;
                private String flag;
            
                public TableBean() {
                }
            
                public String getId() {
                    return id;
                }
            
                public void setId(String id) {
                    this.id = id;
                }
            
                public String getPid() {
                    return pid;
                }
            
                public void setPid(String pid) {
                    this.pid = pid;
                }
            
                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;
                }
            
                public String getFlag() {
                    return flag;
                }
            
                public void setFlag(String flag) {
                    this.flag = flag;
                }
            
                @Override
                public void write(DataOutput dataOutput) throws IOException {
                    dataOutput.writeUTF(id);
                    dataOutput.writeUTF(pid);
                    dataOutput.writeInt(amount);
                    dataOutput.writeUTF(pname);
                    dataOutput.writeUTF(flag);
                }
            
                @Override
                public void readFields(DataInput dataInput) throws IOException {
                    this.id = dataInput.readUTF();
                    this.pid = dataInput.readUTF();
                    this.amount = dataInput.readInt();
                    this.pname = dataInput.readUTF();
                    this.flag = dataInput.readUTF();
                }
            
                @Override
                public String toString() {
                    return id + "\t" + pname +  "\t" + amount;
                }
            }
            
        • TableMapper

          • package com.lotuslaw.mapreduce.reducejoin;
            
            import org.apache.hadoop.io.LongWritable;
            import org.apache.hadoop.io.Text;
            import org.apache.hadoop.mapreduce.InputSplit;
            import org.apache.hadoop.mapreduce.Mapper;
            import org.apache.hadoop.mapreduce.lib.input.FileSplit;
            
            import java.io.IOException;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.reducejoin
             * @create: 2021-11-23 18:28
             * @description:
             */
            public class TableMapper extends Mapper<LongWritable, Text, Text, TableBean> {
            
                private String filename;
                private Text outK = new Text();
                private TableBean outV = new TableBean();
            
                @Override
                protected void setup(Context context) throws IOException, InterruptedException {
                    // 初始化
                    FileSplit split = (FileSplit) context.getInputSplit();
            
                    filename = split.getPath().getName();
                }
            
                @Override
                protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
                    // 获取一行
                    String line = value.toString();
            
                    // 判断是哪个文件的
                    if (filename.contains("order")){
                        String[] split = line.split("\t");
            
                        // 封装
                        outK.set(split[1]);
                        outV.setId(split[0]);
                        outV.setPid(split[1]);
                        outV.setAmount(Integer.parseInt(split[2]));
                        outV.setPname("");
                        outV.setFlag("order");
                    }else {
                        String[] split = line.split("\t");
            
                        outK.set(split[0]);
                        outV.setId("");
                        outV.setPid(split[0]);
                        outV.setAmount(0);
                        outV.setPname(split[1]);
                        outV.setFlag("pd");
                    }
            
                    // 写出
                    context.write(outK, outV);
                }
            }
            
            
        • TableReducer类

          • package com.lotuslaw.mapreduce.reducejoin;
            
            import org.apache.commons.beanutils.BeanUtils;
            import org.apache.hadoop.io.NullWritable;
            import org.apache.hadoop.io.Text;
            import org.apache.hadoop.mapreduce.Reducer;
            
            import java.io.IOException;
            import java.lang.reflect.InvocationTargetException;
            import java.util.ArrayList;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.reducejoin
             * @create: 2021-11-23 18:41
             * @description:
             */
            public class TableReducer extends Reducer<Text, TableBean, TableBean, NullWritable> {
                @Override
                protected void reduce(Text key, Iterable<TableBean> values, Context context) throws IOException, InterruptedException {
            
                    // 准备初始化集合
                    ArrayList<TableBean> orderBeans = new ArrayList<>();
                    TableBean pdBean = new TableBean();
            
                    // 循环遍历
                    for (TableBean value : values) {
                        if ("order".equals(value.getFlag())) {
                            TableBean tmptableBean = new TableBean();
                            try {
                                BeanUtils.copyProperties(tmptableBean, value);
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            }
                            orderBeans.add(tmptableBean);
                        }else {
                            try {
                                BeanUtils.copyProperties(pdBean, value);
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            }
                        }
                    }
            
                    // 循环遍历orderBeans,复制pdname
                    for (TableBean orderBean : orderBeans) {
                        orderBean.setPname(pdBean.getPname());
                        context.write(orderBean, NullWritable.get());
                    }
                }
            }
            
        • TableDriver

          • package com.lotuslaw.mapreduce.reducejoin;
            
            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;
            
            import java.io.IOException;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.reducejoin
             * @create: 2021-11-23 18:51
             * @description:
             */
            public class TableDriver {
                public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException, IOException {
                    Job job = Job.getInstance(new Configuration());
            
                    job.setJarByClass(TableDriver.class);
                    job.setMapperClass(TableMapper.class);
                    job.setReducerClass(TableReducer.class);
            
                    job.setMapOutputKeyClass(Text.class);
                    job.setMapOutputValueClass(TableBean.class);
            
                    job.setOutputKeyClass(TableBean.class);
                    job.setOutputValueClass(NullWritable.class);
            
                    FileInputFormat.setInputPaths(job, new Path("D:\\7-bigdata\\test_data\\input5"));
                    FileOutputFormat.setOutputPath(job, new Path("D:\\7-bigdata\\test_data\\output6"));
            
                    boolean b = job.waitForCompletion(true);
                    System.exit(b ? 0 : 1);
                }
            }
            
      • Map Join

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

        • 优点:在Reduce端处理过多的表,非常容易产生数据倾斜,在Map端缓存多张表,提前处理业务逻辑,这样增加Map端业务,减少Reduce端数据的压力,尽可能的减少数据倾斜

        • 具体办法:采用DistributedCache

          • 在Mapper的setup阶段,将问价读取到缓存集合中
          • 在Driver驱动类中加载缓存
        • 在MapJoinDriver驱动类中添加缓存文件

          • package com.lotuslaw.mapreduce.mapjoin;
            
            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;
            
            import java.io.IOException;
            import java.net.URI;
            import java.net.URISyntaxException;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.mapjoin
             * @create: 2021-11-23 19:48
             * @description:
             */
            public class MapJoinDriver {
                public static void main(String[] args) throws IOException, URISyntaxException, ClassNotFoundException, InterruptedException, IOException, URISyntaxException {
            
                    // 1 获取job信息
                    Configuration conf = new Configuration();
                    Job job = Job.getInstance(conf);
                    // 2 设置加载jar包路径
                    job.setJarByClass(MapJoinDriver.class);
                    // 3 关联mapper
                    job.setMapperClass(MapJoinMapper.class);
                    // 4 设置Map输出KV类型
                    job.setMapOutputKeyClass(Text.class);
                    job.setMapOutputValueClass(NullWritable.class);
                    // 5 设置最终输出KV类型
                    job.setOutputKeyClass(Text.class);
                    job.setOutputValueClass(NullWritable.class);
            
                    // 加载缓存数据
                    job.addCacheFile(new URI("file:///D:/7-bigdata/test_data/tablecache/pd.txt"));
                    // Map端Join的逻辑不需要Reduce阶段,设置reduceTask数量为0
                    job.setNumReduceTasks(0);
            
                    // 6 设置输入输出路径
                    FileInputFormat.setInputPaths(job, new Path("D:\\7-bigdata\\test_data\\input5"));
                    FileOutputFormat.setOutputPath(job, new Path("D:\\7-bigdata\\test_data\\output7"));
                    // 7 提交
                    boolean b = job.waitForCompletion(true);
                    System.exit(b ? 0 : 1);
                }
            }
            
        • MapJoinMapper类

          • package com.lotuslaw.mapreduce.mapjoin;
            
            import org.apache.commons.lang.StringUtils;
            import org.apache.hadoop.fs.FSDataInputStream;
            import org.apache.hadoop.fs.FileSystem;
            import org.apache.hadoop.fs.Path;
            import org.apache.hadoop.io.IOUtils;
            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.BufferedReader;
            import java.io.IOException;
            import java.io.InputStreamReader;
            import java.net.URI;
            import java.util.HashMap;
            
            /**
             * @author: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.mapjoin
             * @create: 2021-11-23 19:56
             * @description:
             */
            public class MapJoinMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
            
                private HashMap<String, String> pdMap = new HashMap<String, String>();
                private Text outK = new Text();
            
                @Override
                protected void setup(Context context) throws IOException, InterruptedException {
                    // 获取缓存的文件并把文件内容封装到集合
                    URI[] cacheFiles = context.getCacheFiles();
                    FileSystem fs = FileSystem.get(context.getConfiguration());
                    FSDataInputStream fis = fs.open(new Path(cacheFiles[0]));
            
                    // 从流中读取数据
                    BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
                    String line;
                    while (StringUtils.isNotEmpty(line=reader.readLine())) {
                        // 切割
                        String[] fields = line.split("\t");
            
                        // 赋值
                        pdMap.put(fields[0], fields[1]);
                    }
            
                    // 关流
                    IOUtils.closeStream(reader);
                }
            
                @Override
                protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
                    // 处理order.txt
                    String line = value.toString();
                    String[] fields = line.split("\t");
            
                    // 获取pid
                    String pname = pdMap.get(fields[1]);
            
                    // 封装
                    outK.set(fields[0] + "\t" + pname + "\t" + fields[2]);
            
                    context.write(outK, NullWritable.get());
                }
            }
            
    • 数据清洗(ETL)

      • 在运行核心业务MapReduce程序之前,往往要先对数据进行清洗,清理掉不符合用户要求的数据,清理的过程往往只需要运行Mapper程序,不需要运行Reducer程序

      • WebLogMapper类

        • package com.lotuslaw.mapreduce.etl;
          
          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;
          
          /**
           * @author: lotuslaw
           * @version: V1.0
           * @package: com.lotuslaw.mapreduce.etl
           * @create: 2021-11-23 20:17
           * @description:
           */
          public class WebLogMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
              @Override
              protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
                  // 获取一行
                  String line = value.toString();
          
                  // ETL
          
                  // if (fields.matches(check)) {}
          
                  boolean result = parseLong(line, context);
                  if (!result){
                      return;
                  }
          
                  // 写出
                  context.write(value, NullWritable.get());
              }
          
              private boolean parseLong(String line, Context context) {
          
                  // 切割
                  String[] fields = line.split(" ");
                  if (fields.length > 11) {
                      return true;
                  }else {
                      return false;
                  }
              }
          }
          
      • WebLogDriver类

        • package com.lotuslaw.mapreduce.etl;
          
          import com.lotuslaw.mapreduce.outputformat.LogDriver;
          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;
          
          /**
           * @author: lotuslaw
           * @version: V1.0
           * @package: com.lotuslaw.mapreduce.etl
           * @create: 2021-11-23 20:21
           * @description:
           */
          public class WebLogDriver {
              public static void main(String[] args) throws Exception {
          
          // 输入输出路径需要根据自己电脑上实际的输入输出路径设置
                  args = new String[] { "D:\\7-bigdata\\test_data\\input6", "D:\\7-bigdata\\test_data\\output8" };
          
                  // 1 获取job信息
                  Configuration conf = new Configuration();
                  Job job = Job.getInstance(conf);
          
                  // 2 加载jar包
                  job.setJarByClass(LogDriver.class);
          
                  // 3 关联map
                  job.setMapperClass(WebLogMapper.class);
          
                  // 4 设置最终输出类型
                  job.setOutputKeyClass(Text.class);
                  job.setOutputValueClass(NullWritable.class);
          
                  // 设置reducetask个数为0
                  job.setNumReduceTasks(0);
          
                  // 5 设置输入和输出路径
                  FileInputFormat.setInputPaths(job, new Path(args[0]));
                  FileOutputFormat.setOutputPath(job, new Path(args[1]));
          
                  // 6 提交
                  boolean b = job.waitForCompletion(true);
                  System.exit(b ? 0 : 1);
              }
          }
          
    • MapReduce开发总结

      • 输入数据接口:InputFormat
        • 默认使用的实现类是TextInputFormat
        • TextInputFormat的功能逻辑是:一次读一行文本,然后将该行的起始偏移量作为key,将内容作为value返回
        • CombineTextInputFormat可以把多个小文件合并成一个切片处理,提高处理效率
      • 逻辑处理接口:Mapper
        • 用户根据业务需求实现其中三个方法:map() setup() cleanup()
      • Partitioner分区
        • 有默认实现HashPartitioner,逻辑是根据key的哈希值和numReduces来返回一个分区号:key.hashCode()&Integer.MAXVALUE % numReduces
        • 如果业务上有特别的需求,可以自定义分区
      • Comparable排序
        • 当我们用自定义的对象作为key来输出时,就必须要实现WritableComparable接口,重写其中的compareTo()方法
        • 部分排序:对最终输出端每一个文件进行内部排序
        • 全排序:对所有数据进行排序,通常只有一个Reduce
        • 二次排序:排序的条件有两个及以上
      • Combiner合并
        • Combiner合并可以提高程序执行效率,减少IO传输,但是使用时必须不能影响原有的业务处理结果
      • 逻辑处理接口:Reducer
        • 用户根据业务需求实现其中三个方法:reduce() setup() cleanup()
      • 输出数据接口:OutputFormat
        • 默认实现类是TextOutputFormat,功能逻辑是:将每一个KV对,向目标文本文件输出一行
        • 用户还可以自定义OutputFormat

    Hadoop数据压缩

    • 概述

      • 压缩的好处和坏处
        • 压缩的优点:以减少磁盘IO、减少磁盘存储空间
        • 压缩的缺点:增加CPU开销
      • 压缩原则
        • 运算密集型的Job,少用压缩
        • IO密集型的Job,多用压缩
    • MR支持的压缩编码

      • 压缩算法对比介绍

        • 压缩格式 Hadoop自带? 算法 文件扩展名 是否可切片 换成压缩格式后,原来的程序是否需要修改
          DEFLATE 是,直接使用 DEFLATE .deflate 和文本处理一样,不需要修改
          Gzip 是,直接使用 DEFLATE .gz 和文本处理一样,不需要修改
          bzip2 是,直接使用 bzip2 .bz2 和文本处理一样,不需要修改
          LZO 否,需要安装 LZO .lzo 需要建索引,还需要指定输入格式
          Snappy 是,直接使用 Snappy .snappy 和文本处理一样,不需要修改
      • 压缩性能的比较

        • 压缩算法 原始文件大小 压缩文件大小 压缩速度 解压速度
          gzip 8.3GB 1.8GB 17.5MB/s 58MB/s
          bzip2 8.3GB 1.1GB 2.4MB/s 9.5MB/s
          LZO 8.3GB 2.9GB 49.3MB/s 74.6MB/s
        • # http://google.github.io/snappy/
          Snappy is a compression/decompression library. It does not aim for maximum compression, or compatibility with any other compression library; instead, it aims for very high speeds and reasonable compression. For instance, compared to the fastest mode of zlib, Snappy is an order of magnitude faster for most inputs, but the resulting compressed files are anywhere from 20% to 100% bigger.On a single core of a Core i7 processor in 64-bit mode, Snappy compresses at about 250 MB/sec or more and decompresses at about 500 MB/sec or more.
          
    • 压缩方式的选择

      • 压缩方式选择时重点考虑:压缩/解压缩速度、压缩率(压缩后存储大小)、压缩后是否可以支持切片

      • Gzip压缩

        • 优点:压缩率比较高
        • 缺点:不知此Split;压缩/解压速度一般
      • Bzip2压缩

        • 优点:压缩率高;支持Split
        • 缺点:压缩/解压速度慢
      • Lzo压缩

        • 优点:压缩/解压速度比较快;至此Split
        • 缺点:压缩率一般;想支持切片需要额外创建索引
      • Snappy压缩

        • 优点:压缩和解压缩速度快
        • 缺点:不支持Split;压缩率一般
      • 压缩位置选择

      • 压缩参数配置

        • 压缩格式 对应的编码/解码器
          DEFLATE org.apache.hadoop.io.compress.DefaultCodec
          gzip org.apache.hadoop.io.compress.GzipCodec
          bzip2 org.apache.hadoop.io.compress.BZip2Codec
          LZO com.hadoop.compression.lzo.LzopCodec
          Snappy org.apache.hadoop.io.compress.SnappyCodec
        • 要在Hadoop中启用压缩,可以配置如下参数

    • 压缩实操

      • Map输出端采用压缩、Reduce输出端采用压缩

        • Driver

          • package com.lotuslaw.mapreduce.compress;
            
            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.io.compress.BZip2Codec;
            import org.apache.hadoop.io.compress.CompressionCodec;
            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: lotuslaw
             * @version: V1.0
             * @package: com.lotuslaw.mapreduce.wordcount
             * @create: 2021-11-23 9:51
             * @description:
             */
            /*
            atguigu	2
            banzhang	1
            cls	2
            hadoop	1
            jiao	1
            ss	2
            xue	1
             */
            public class WordCountDriver {
                public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
            
                    // 获取job
                    Configuration conf = new Configuration();
                    Job job = Job.getInstance(conf);
            
                    // 开启map端输出压缩
                    conf.setBoolean("mapreduce.map.output.compress", true);
            
                    // 设置map端输出压缩方式
                    conf.setClass("mapreduce.map.output.compress.codec", BZip2Codec.class, CompressionCodec.class);
            
                    // 设置reduce输出端开启压缩
                    FileOutputFormat.setCompressOutput(job, true);
            
                    // 设置压缩方式
                    FileOutputFormat.setOutputCompressorClass(job, BZip2Codec.class);
            
                    // 设置jar包路径
                    job.setJarByClass(WordCountDriver.class);
            
                    // 关联mapper和reducer
                    job.setMapperClass(WordCountMapper.class);
                    job.setReducerClass(WordCountReducer.class);
            
                    // 设置map输出的kv类型
                    job.setMapOutputKeyClass(Text.class);
                    job.setMapOutputValueClass(IntWritable.class);
            
                    // 设置最终输出的kv类型
                    job.setMapOutputKeyClass(Text.class);
                    job.setOutputValueClass(IntWritable.class);
            
                    // 设置输入路径和输出路径
                    // mapreduce程序中,如果输出路径存在,则直接报错
                    FileInputFormat.setInputPaths(job, new Path("D:\\7-bigdata\\test_data\\input"));
                    FileOutputFormat.setOutputPath(job, new Path("D:\\7-bigdata\\test_data\\output10"));
            
                    // 提交job
                    boolean result = job.waitForCompletion(true);
            
                    System.exit(result ? 0 : 1);
                }
            }
            
  • 相关阅读:
    ArcGIS Server如何发布gp服务2
    ArcGIS Engine之ILayer、IFeatureLayer和IFeatureClass的关系
    ArcGIS Server添加数据源之后无法启动。。
    ArcGIS Server动态图层的数据源
    ModelBuilder
    如何在Windows Server 2016启用或关闭Internet Explorer增强的安全配置
    ArcGIS 10.2.2 补丁
    ArcGIS GP选项设置
    Internet Explorer安全设置解决ArcGIS Server无法加载解析.sde文件
    基于 ArcGIS Engine 的水质模拟预测研究 ——以黄河兰州段为例
  • 原文地址:https://www.cnblogs.com/lotuslaw/p/15598449.html
Copyright © 2020-2023  润新知