美文网首页
6_大数据之MapReduce_1

6_大数据之MapReduce_1

作者: 十丈_红尘 | 来源:发表于2019-05-30 16:04 被阅读0次

    MapReduce概述

    1️⃣MapReduce定义

    2️⃣MapReduce优缺点

    1. 优点
    2. 缺点

    3️⃣MapReduce核心思想

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

    4️⃣MapReduce进程

    5️⃣官方WordCount源码
      采用反编译工具反编译源码,发现WordCount案例有Map类、Reduce类和驱动类。且数据的类型是Hadoop自身封装的序列化类型。

    6️⃣常用数据序列化类型

    7️⃣MapReduce编程规范 : 用户编写的程序分成三个部分:MapperReducerDriver

    8️⃣WordCount案例实操

    1. 需求 : 在给定的文本文件中统计输出每一个单词出现的总次数
      (1)输入数据
    ffadsfsda
    fasdfsad
    fsadfa
    Fsadfa
    fsadfa
    Ffadsfsda
    

     (2)期望输出数据

    Ffadsfsda  1
    Fsadfa 1
    fasdfsad   1
    ffadsfsda  1
    fsadfa 2
    

    2.需求分析:按照MapReduce编程规范,分别编写MapperReducerDriver

    1. 编写程序
      (1)创建一个Maven工程
      (2)在pom.xml文件中添加如下依赖
    <dependencies>
          <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>RELEASE</version>
          </dependency>
          <dependency>
              <groupId>org.apache.logging.log4j</groupId>
              <artifactId>log4j-core</artifactId>
              <version>2.8.2</version>
          </dependency>
          <dependency>
              <groupId>org.apache.hadoop</groupId>
              <artifactId>hadoop-common</artifactId>
              <version>2.7.2</version>
          </dependency>
          <dependency>
              <groupId>org.apache.hadoop</groupId>
              <artifactId>hadoop-client</artifactId>
              <version>2.7.2</version>
          </dependency>
          <dependency>
              <groupId>org.apache.hadoop</groupId>
              <artifactId>hadoop-hdfs</artifactId>
              <version>2.7.2</version>
          </dependency>
    </dependencies>
    

     (3)在项目的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
    

     (4)编写Mapper

    public class WordcountMapper extends Mapper<LongWritable, Text, Text, IntWritable>{
      
      Text k = new Text();
      IntWritable v = new IntWritable(1);
      
      @Override
      protected void map(LongWritable key, Text value, Context context)   throws IOException, InterruptedException {
          
          // 1 获取一行
          String line = value.toString();
          
          // 2 切割
          String[] words = line.split(" ");
          
          // 3 输出
          for (String word : words) {
              k.set(word);
              context.write(k, v);
          }
      }
    }
    

     (5)编写Reducer

    public class WordcountReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
    
         int sum;
         IntWritable v = new IntWritable();
    
         @Override
         protected void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {
          
              // 1 累加求和
              sum = 0;
              for (IntWritable count : values) {
                  sum += count.get();
              }
          
              // 2 输出
              v.set(sum);
              context.write(key,v);
         }
    }
    

     (6)编写Driver驱动类

    public class WordcountDriver {
    
      public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
    
          // 1 获取配置信息以及封装任务
          Configuration configuration = new Configuration();
          Job job = Job.getInstance(configuration);
    
          // 2 设置jar加载路径
          job.setJarByClass(WordcountDriver.class);
    
          // 3 设置map和reduce类
          job.setMapperClass(WordcountMapper.class);
          job.setReducerClass(WordcountReducer.class);
    
          // 4 设置map输出
          job.setMapOutputKeyClass(Text.class);
          job.setMapOutputValueClass(IntWritable.class);
    
          // 5 设置最终输出kv类型
          job.setOutputKeyClass(Text.class);
          job.setOutputValueClass(IntWritable.class);
          
          // 6 设置输入和输出路径
          FileInputFormat.setInputPaths(job, new Path(args[0]));
          FileOutputFormat.setOutputPath(job, new Path(args[1]));
    
          // 7 提交
          boolean result = job.waitForCompletion(true);
    
          System.exit(result ? 0 : 1);
      }
    }
    

    9️⃣集群上测试
    (1)用mavenjar包,需要添加的打包插件依赖(注意:标记红颜色的部分需要替换为自己工程主类)

    <build>
          <plugins>
              <plugin>
                  <artifactId>maven-compiler-plugin</artifactId>
                  <version>2.3.2</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>
                      <archive>
                          <manifest>
                              <mainClass>com.xxx.mr.WordcountDriver</mainClass>
                          </manifest>
                      </archive>
                  </configuration>
                  <executions>
                      <execution>
                          <id>make-assembly</id>
                          <phase>package</phase>
                          <goals>
                              <goal>single</goal>
                          </goals>
                      </execution>
                  </executions>
              </plugin>
          </plugins>
    </build>
    

    注意:如果工程上显示红叉。在项目上右键->maven->update project即可。
    (1)将程序打成jar包,然后拷贝到Hadoop集群中
    步骤详情:右键->Run as->maven install。等待编译完成就会在项目的target文件夹中生成jar包。如果看不到。在项目上右键-》Refresh,即可看到。修改不带依赖的jar包名称为wc.jar,并拷贝该jar包到Hadoop集群。
    (2)启动Hadoop集群
    (3)执行WordCount程序

    hadoop jar  wc.jar com.xxx.wordcount.WordcountDriver /user/xxx/input /user/xxx/output
    

    Hadoop序列化

    1️⃣序列化概述

    2️⃣自定义bean对象实现序列化接口(Writable)
     在企业开发中往往常用的基本序列化类型不能满足所有需求,比如在Hadoop框架内部传递一个bean对象,那么该对象就需要实现序列化接口。具体实现bean对象序列化步骤如下7步:
    (1)必须实现Writable接口
    (2)反序列化时,需要反射调用空参构造函数,所以必须有空参构造

    public FlowBean() {
      super();
    }
    

    (3)重写序列化方法

    @Override
    public void write(DataOutput out) throws IOException {
      out.writeLong(upFlow);
      out.writeLong(downFlow);
      out.writeLong(sumFlow);
    }
    

    (4)重写反序列化方法

    @Override
    public void readFields(DataInput in) throws IOException {
      upFlow = in.readLong();
      downFlow = in.readLong();
      sumFlow = in.readLong();
    }
    

    (5)注意反序列化的顺序和序列化的顺序完全一致
    (6)要想把结果显示在文件中,需要重写toString(),可用”\t”分开,方便后续用。
    (7)如果需要将自定义的bean放在key中传输,则还需要实现Comparable接口,因为MapReduce框中的Shuffle过程要求对key必须能排序。详见后面排序案例。

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

    3️⃣序列化案例实操
     1. 需求 : 统计每一个手机号耗费的总上行流量、下行流量、总流量;
    (1)输入数据

    id     手机号码         网络ip        上行流量  下行流量     网络状态码
    1   1363157985066  120.196.100.82    2481     24681       200
    2   1363157995052  120.197.40.4      264      0           200
    3   1363157991076  120.196.100.99    132      1512        200
    4   1363154400022  120.197.40.4      240      0           200
    5   1363157993044  120.196.100.99    1527     2106        200
    6   1363157995074  120.197.40.4      4116     1432        200
    7   1363157993055  120.196.100.99    1116     954         200
    8   1363157995033  120.197.40.4      3156     2936        200
    9   1363157983019  120.196.100.82    240      0           200
    10  1363157984041  120.197.40.4      6960     690         200
    11  1363157973098  120.197.40.4      3659     3538        200
    12  1363157986029  120.196.100.99    1938     180         200
    13  1363157992093  120.196.100.99    918      4938        200
    14  1363157986041  120.197.40.4      180      180         200
    15  1363157984040  120.197.40.4      1938     2910        200
    16  1363157995093  120.196.100.82    3008     3720        200
    17  1363157982040  120.196.100.99    7335     110349      200
    18  1363157986072  120.196.100.99    9531     2412        200
    19  1363157990043  120.196.100.55    11058    48243       200
    20  1363157988072  120.196.100.82    120      120         200
    21  1363157985066  120.196.100.82    2481     24681       200
    22  1363157993055  120.196.100.99    1116     954         200
    

    (2)期望输出数据格式:

     手机号码      上行流量  下行流量  总流量
    13560436666    1116     954    2070
    

     2. 需求分析


     3.编写MapReduce程序
    (1)编写流量统计的Bean对象
    package com.xxx.mapreduce.flowsum;
    import java.io.DataInput;
    import java.io.DataOutput;
    import java.io.IOException;
    import org.apache.hadoop.io.Writable;
    
    // 1 实现writable接口
    public class FlowBean implements Writable{
    
      private long upFlow;
      private long downFlow;
      private long sumFlow;
      
      //2  反序列化时,需要反射调用空参构造函数,所以必须有
      public FlowBean() {
          super();
      }
    
      public FlowBean(long upFlow, long downFlow) {
          super();
          this.upFlow = upFlow;
          this.downFlow = downFlow;
          this.sumFlow = upFlow + downFlow;
      }
      
      //3  写序列化方法
      @Override
      public void write(DataOutput out) throws IOException {
          out.writeLong(upFlow);
          out.writeLong(downFlow);
          out.writeLong(sumFlow);
      }
      
      //4 反序列化方法
      //5 反序列化方法读顺序必须和写序列化方法的写顺序必须一致
      @Override
      public void readFields(DataInput in) throws IOException {
          this.upFlow  = in.readLong();
          this.downFlow = in.readLong();
          this.sumFlow = in.readLong();
      }
    
      // 6 编写toString方法,方便后续打印到文本
      @Override
      public String toString() {
          return upFlow + "\t" + downFlow + "\t" + 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;
      }
    }
    

    (2)编写Mapper

    package com.xxx.mapreduce.flowsum;
    import java.io.IOException;
    import org.apache.hadoop.io.LongWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Mapper;
    
    public class FlowCountMapper extends Mapper<LongWritable, Text, Text, FlowBean>{
      
      FlowBean v = new FlowBean();
      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 封装对象
          // 取出手机号码
          String phoneNum = fields[1];
    
          // 取出上行流量和下行流量
          long upFlow = Long.parseLong(fields[fields.length - 3]);
          long downFlow = Long.parseLong(fields[fields.length - 2]);
    
          k.set(phoneNum);
          v.set(downFlow, upFlow);
          
          // 4 写出
          context.write(k, v);
      }
    }
    

    (3)编写Reducer

    package com.xxx.mapreduce.flowsum;
    import java.io.IOException;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Reducer;
    
    public class FlowCountReducer extends Reducer<Text, FlowBean, Text, FlowBean> {
    
      @Override
      protected void reduce(Text key, Iterable<FlowBean> values, Context context)throws IOException, InterruptedException {
    
          long sum_upFlow = 0;
          long sum_downFlow = 0;
    
          // 1 遍历所用bean,将其中的上行流量,下行流量分别累加
          for (FlowBean flowBean : values) {
              sum_upFlow += flowBean.getUpFlow();
              sum_downFlow += flowBean.getDownFlow();
          }
    
          // 2 封装对象
          FlowBean resultBean = new FlowBean(sum_upFlow, sum_downFlow);
          
          // 3 写出
          context.write(key, resultBean);
      }
    }
    

    (4)编写Driver驱动类

    package com.xxx.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:/input/inputflow", "e:/output1" };
    
          // 1 获取配置信息,或者job对象实例
          Configuration configuration = new Configuration();
          Job job = Job.getInstance(configuration);
    
          // 6 指定本程序的jar包所在的本地路径
          job.setJarByClass(FlowsumDriver.class);
    
          // 2 指定本业务job要使用的mapper/Reducer业务类
          job.setMapperClass(FlowCountMapper.class);
          job.setReducerClass(FlowCountReducer.class);
    
          // 3 指定mapper输出数据的kv类型
          job.setMapOutputKeyClass(Text.class);
          job.setMapOutputValueClass(FlowBean.class);
    
          // 4 指定最终输出的数据的kv类型
          job.setOutputKeyClass(Text.class);
          job.setOutputValueClass(FlowBean.class);
          
          // 5 指定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);
      }
    }
    

    MapReduce框架原理

    1️⃣ InputFormat数据输入


    1.1 切片与MapTask并行度决定机制
      MapTask的并行度决定Map阶段的任务处理并发度,进而影响到整个Job的处理速度。
      思考:1G的数据,启动8MapTask,可以提高集群的并发处理能力。那么1K的数据,也启动8MapTask,会提高集群性能吗?MapTask并行任务是否越多越好呢?哪些因素影响了MapTask并行度?
    1.MapTask并行度决定机制
     数据块:BlockHDFS物理上把数据分成一块一块。
     数据切片:数据切片只是在逻辑上对输入进行分片,并不会在磁盘上将其切分成片进行存储。
    2️⃣ Job提交流程源码和切片源码详解
    1.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());
    
    2.FileInputFormat切片源码解析(input.getSplits(job))
    3️⃣FileInputFormat切片机制
    4️⃣CombineTextInputFormat切片机制
      框架默认的TextInputFormat切片机制是对任务按文件规划切片,不管文件多小,都会是一个单独的切片,都会交给一个MapTask,这样如果有大量小文件,就会产生大量的MapTask,处理效率极其低下。
     1、应用场景:
    CombineTextInputFormat用于小文件过多的场景,它可以将多个小文件从逻辑上规划到一个切片中,这样,多个小文件就可以交给一个MapTask处理。
     2、虚拟存储切片最大值设置
    CombineTextInputFormat.setMaxInputSplitSize(job, 4194304);// 4m
    注意:虚拟存储切片最大值设置最好根据实际的小文件大小情况来设置具体的值。
     3、切片机制
     生成切片过程包括:虚拟存储过程和切片过程二部分。
     (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
    5️⃣CombineTextInputFormat案例实操
    1.需求 : 将输入的大量小文件合并成一个切片统一处理。
    (1)输入数据 : 准备4个小文件
    (2)期望 : 期望一个切片处理4个文件
    2.实现过程
    (1)不做任何处理,运行1.6节的WordCount案例程序,观察切片个数为4. (2)在WordcountDriver中增加如下代码,运行程序,并观察运行的切片个数为3。
     (a)驱动类中添加代码如下:
    // 如果不设置InputFormat,它默认用的是TextInputFormat.class
    job.setInputFormatClass(CombineTextInputFormat.class);
    
    //虚拟存储切片最大值设置4m
    CombineTextInputFormat.setMaxInputSplitSize(job, 4194304);
    

     (b)运行如果为3个切片。

    (3)在WordcountDriver中增加如下代码,运行程序,并观察运行的切片个数为1。
     (a)驱动中添加代码如下:
    // 如果不设置InputFormat,它默认用的是TextInputFormat.class
    job.setInputFormatClass(CombineTextInputFormat.class);
    
    //虚拟存储切片最大值设置20m
    CombineTextInputFormat.setMaxInputSplitSize(job, 20971520);
    

     (b)运行如果为1个切片。


    6️⃣FileInputFormat实现类
    7️⃣KeyValueTextInputFormat使用案例
    1.需求 : 统计输入文件中每一行的第一个单词相同的行数。
    (1)输入数据
    banzhang ni hao
    xihuan hadoop banzhang
    banzhang ni hao
    xihuan hadoop banzhang
    

    (2)期望结果数据

    banzhang   2
    xihuan 2
    

    2.需求分析

    3.代码实现
    (1)编写Mapper
    package com.xxx.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.xxx.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.xxx.mapreduce.keyvaleTextInputFormat;
    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);
      }
    }
    

    8️⃣NLineInputFormat使用案例
    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
    2.需求分析

    3.代码实现
    (1)编写Mapper
    package com.xxx.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.xxx.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.xxx.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);  
      }
    }
    

    9️⃣自定义InputFormat


    🔟自定义InputFormat案例实操
     无论HDFS还是MapReduce,在处理小文件时效率都非常低,但又难免面临处理大量小文件的场景,此时,就需要有相应解决方案。可以自定义InputFormat实现小文件的合并。
    1.需求 : 将多个小文件合并成一个SequenceFile文件(SequenceFile文件是Hadoop用来存储二进制形式的key-value对的文件格式),SequenceFile里面存储着多个文件,存储的形式为文件路径+名称为key,文件内容为value
    (1)输入数据
    //one.txt
    yongpeng weidong weinan
    sanfeng luozong xiaoming
    
    //two.txt
    longlong fanfan
    mazong kailun yuhang yixin
    longlong fanfan
    mazong kailun yuhang yixin
    
    //three.txt
    shuaige changmo zhenqiang 
    dongli lingu xuanxuan
    

    (2)期望输出文件格式
    2.需求分析

    3.程序实现
    (1)自定义InputFromat
    package com.xxx.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.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;
    
    // 定义类继承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.xxx.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.NullWritable;
    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 获取文件系统
                  Path path = split.getPath();
                  fs = path.getFileSystem(configuration);
                  
                  // 3 读取数据
                  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)编写SequenceFileMapper类处理流程

    package com.xxx.mapreduce.inputformat;
    import java.io.IOException;
    import org.apache.hadoop.io.BytesWritable;
    import org.apache.hadoop.io.NullWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Mapper;
    import org.apache.hadoop.mapreduce.lib.input.FileSplit;
    
    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)编写SequenceFileReducer类处理流程

    package com.xxx.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)编写SequenceFileDriver类处理流程

    package com.xxx.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);
      }
    }
    

    MapReduce工作流程 MapReduce详细工作流程1 MapReduce详细工作流程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()方法)

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

    源码解析流程

    context.write(k, NullWritable.get());
    output.write(key, value);
    collector.collect(key, value,partitioner.getPartition(key, value, partitions));
    HashPartitioner();
    collect()
    close()
    collect.flush()
    sortAndSpill()
    sort()   QuickSort
    mergeParts();
    collector.close();
    

    相关文章

      网友评论

          本文标题:6_大数据之MapReduce_1

          本文链接:https://www.haomeiwen.com/subject/sqqvtctx.html