java大数据最全课程学习笔记(6)--MapReduce精通(二)--MapReduce框架原理

目前CSDN,博客园,简书同步发表中,更多精彩欢迎访问我的gitee pages

MapReduce精通(二)

MapReduce框架原理

MapReduce工作流程

  1. 流程示意图

  1. 流程详解

    上面的流程是整个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。

  2. 源码解析流程

    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();

InputFormat数据输入

切片与MapTask并行度决定机制

  1. 问题引出

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

    思考:1G的数据,启动8个MapTask,提高的并发处理能力。那么1K的数据,也启动8个MapTask吗?MapTask并行任务是否越多越好呢?

  2. MapTask并行度决定机制

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

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

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());

  1. FileInputFormat切片源码解析(input.getSplits(job))
public List<InputSplit> getSplits(JobContext job) throws IOException {
StopWatch sw = new StopWatch().start();
// minSize从mapreduce.input.fileinputformat.split.minsize和1之间对比,取最大值
long minSize = Math.max(getFormatMinSplitSize(), getMinSplitSize(job));
// 读取mapreduce.input.fileinputformat.split.maxsize,如果没有设置使用Long.MaxValue作为默认值
    long maxSize = getMaxSplitSize(job);

    // generate splits
List<InputSplit> splits = new ArrayList<InputSplit>();
// 获取当前Job输入目录中所有文件的状态(元数据)
List<FileStatus> files = listStatus(job);
// 以文件为单位进行切片
    for (FileStatus file: files) {
      Path path = file.getPath();
      long length = file.getLen();
      if (length != 0) {
        BlockLocation[] blkLocations;
        if (file instanceof LocatedFileStatus) {
          blkLocations = ((LocatedFileStatus) file).getBlockLocations();
        } else {
          FileSystem fs = path.getFileSystem(job.getConfiguration());
          blkLocations = fs.getFileBlockLocations(file, 0, length);
        }
      // 判断当前文件是否可切,如果可切,切片
        if (isSplitable(job, path)) {
          long blockSize = file.getBlockSize();
          long splitSize = computeSplitSize(blockSize, minSize, maxSize);
           // 声明待切部分数据的余量
          long bytesRemaining = length;
// 如果 待切部分 / 片大小  > 1.1,先切去一片,再判断
          while (((double) bytesRemaining)/splitSize > SPLIT_SLOP) {
            int blkIndex = getBlockIndex(blkLocations, length-bytesRemaining);
            splits.add(makeSplit(path, length-bytesRemaining, splitSize,
                        blkLocations[blkIndex].getHosts(),
                        blkLocations[blkIndex].getCachedHosts()));
            bytesRemaining -= splitSize;
          }
// 否则,将剩余部分整个作为1片。 最后一片有可能超过片大小,但是不超过其1.1倍
          if (bytesRemaining != 0) {
            int blkIndex = getBlockIndex(blkLocations, length-bytesRemaining);
            splits.add(makeSplit(path, length-bytesRemaining, bytesRemaining,
                       blkLocations[blkIndex].getHosts(),
                       blkLocations[blkIndex].getCachedHosts()));
          }
        } else { // not splitable
         // 如果不可切,整个文件作为1片!
          splits.add(makeSplit(path, 0, length, blkLocations[0].getHosts(),
                      blkLocations[0].getCachedHosts()));
        }
      } else { 
        //Create empty hosts array for zero length files
// 如果文件是个空文件,创建一个切片对象,这个切片从当前文件的0offset起,向后读取0个字节
        splits.add(makeSplit(path, 0, length, new String[0]));
      }
    }
    // Save the number of input files for metrics/loadgen
    job.getConfiguration().setLong(NUM_INPUT_FILES, files.size());
    sw.stop();
    if (LOG.isDebugEnabled()) {
      LOG.debug("Total # of splits generated by getSplits: " + splits.size()
          + ", TimeTaken: " + sw.now(TimeUnit.MILLISECONDS));
    }
    return splits;
  }

FileInputFormat切片机制

  • FileInputFormat切片大小的参数配置

CombineTextInputFormat切片机制

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

  1. 应用场景:

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

  2. 虚拟存储切片最大值设置

    CombineTextInputFormat.setMaxInputSplitSize(job, 4194304);// 4m
    虚拟存储切片最大值设置可以根据实际的小文件大小情况来设置具体的值。

  3. 切片机制

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

    1. 虚拟存储过程:

      1. 将输入目录下所有文件按照文件名称字典顺序一次读入,记录文件大小,并累加计算所有文件的总长度。

      2. 根据是否设置setMaxInputSplitSize值,将每个文件划分成一个一个setMaxInputSplitSize值大小的文件。

      3. 注意:当剩余数据大小超过setMaxInputSplitSize值且不大于2倍setMaxInputSplitSize值,此时将文件均分成2个虚拟存储块(防止出现太小切片)。

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

    2. 切片过程:

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

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

      3. 测试举例:有4个小文件大小分别为1.7M、5.1M、3.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

CombineTextInputFormat案例实操

  1. 需求

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

    1. 输入数据

      准备4个小文件

    2. 期望

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

  2. 实现过程

    1. 随便准备四个小文件,运行WordCount案例实操中的程序,观察切片个数为4

      number of splits:4

    2. 在WordcountDriver中增加如下代码,运行程序,并观察运行的切片个数为1

      1. 驱动类中添加代码如下:

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

        number of splits:1

FileInputFormat实现类

KeyValueTextInputFormat使用案例

  1. 需求

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

    1. 输入数据

      banzhang ni hao

      xihuan hadoop banzhang

      banzhang ni hao

      xihuan hadoop banzhang

      xihuan hadoop banzhang

      banzhang ni hao

      xihuan hadoop banzhang

    2. 期望结果数据

      banzhang 2

      xihuan 2

  2. 需求分析

  3. 代码实现

    1. 编写Mapper类

      package com.atguigu.mapreduce.KeyValueTextInputFormat;
      import java.io.IOException;
      import org.apache.hadoop.io.LongWritable;
      import org.apache.hadoop.io.Text;
      import org.apache.hadoop.mapreduce.Mapper;
      //注意KEYIN和VALUEIN都是Text类型
      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.atguigu.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.atguigu.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, " ");
      		// 获取job对象
      		Job job = Job.getInstance(conf);
      		
      		// 设置jar包位置,关联mapper和reducer
      		job.setJarByClass(KVTextDriver.class);
      		job.setMapperClass(KVTextMapper.class);
      		job.setReducerClass(KVTextReducer.class);
      				
      		// 设置map输出kv类型
      		job.setMapOutputKeyClass(Text.class);
      		job.setMapOutputValueClass(LongWritable.class);
      
      		// 设置最终输出kv类型
      		job.setOutputKeyClass(Text.class);
      job.setOutputValueClass(LongWritable.class);
      		
      		// 设置输入输出数据路径
      		FileInputFormat.setInputPaths(job, new Path(args[0]));
      		
      		// 设置输入格式
      	job.setInputFormatClass(KeyValueTextInputFormat.class);
      		
      		// 设置输出数据路径
      		FileOutputFormat.setOutputPath(job, new Path(args[1]));
      		
      		// 提交job
      		job.waitForCompletion(true);
      	}
      }
      

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.atguigu.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.atguigu.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.atguigu.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);  
      	}
      }
      

自定义InputFormat

自定义InputFormat案例实操

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

  1. 需求

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

    1. 输入数据

    2. 期望输出文件格式(合并后的文件)

      part-r-00000

    3. 需求分析

    4. 代码实现

      1. 自定义InputFromat

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

MapTask工作机制

  1. Read阶段:MapTask通过用户编写的RecordReader,从输入InputSplit中解析出一个个key/value。

  2. Map阶段:该节点主要是将解析出的key/value交给用户编写map()函数处理,并产生一系列新的key/value。

  3. Collect收集阶段:在用户编写map()函数中,当数据处理完成后,一般会调用OutputCollector.collect()输出结果。在该函数内部,它会将生成的key/value分区(调用Partitioner),并写入一个环形内存缓冲区中。

  4. Spill阶段:即“溢写”,当环形缓冲区满后,MapReduce会将数据写到本地磁盘上,生成一个临时文件。需要注意的是,将数据写入本地磁盘之前,先要对数据进行一次本地排序,并在必要时对数据进行合并、压缩等操作。

    溢写阶段详情:

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

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

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

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

Shuffle机制

Shuffle机制

Mapreduce确保每个Reducer的输入都是按key排序的。系统执行排序的过程(即将Mapper输出作为输入传给Reducer)称为Shuffle,如图所示。

Partition分区

Partition分区案例实操

  1. 需求

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

    1. 输入数据

      1 13736230513 192.196.100.1 www.atguigu.com 2481 24681 200

      2 13846544121 192.196.100.2 264 0 200

      3 13956435636 192.196.100.3 132 1512 200

      4 13966251146 192.168.100.1 240 0 404

      5 18271575951 192.168.100.2 www.atguigu.com 1527 2106 200

      6 84188413 192.168.100.3 www.atguigu.com 4116 1432 200

      7 13590439668 192.168.100.4 1116 954 200

      8 15910133277 192.168.100.5 www.hao123.com 3156 2936 200

      9 13729199489 192.168.100.6 240 0 200

      10 13630577991 192.168.100.7 www.shouhu.com 6960 690 200

      11 15043685818 192.168.100.8 www.baidu.com 3659 3538 200

      12 15959002129 192.168.100.9 www.atguigu.com 1938 180 500

      13 13560439638 192.168.100.10 918 4938 200

      14 13470253144 192.168.100.11 180 180 200

      15 13682846555 192.168.100.12 www.qq.com 1938 2910 200

      16 13992314666 192.168.100.13 www.gaga.com 3008 3720 200
      17 13509468723 192.168.100.14 www.qinghua.com 7335 110349 404

      18 18390173782 192.168.100.15 www.sogou.com 9531 2412 200

      19 13975057813 192.168.100.16 www.baidu.com 11058 48243 200

      20 13768778790 192.168.100.17 120 120 200

      21 13568436656 192.168.100.18 www.alibaba.com 2481 24681 200

      22 13568436656 192.168.100.19 1116 954 200

    2. 期望输出数据

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

  2. 需求分析

  1. 在上一章节中的Hadoop序列化之序列化案例实操的基础上,增加一个分区类

    package com.atguigu.mapreduce.flowsum;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Partitioner;
    
    public class ProvincePartitioner extends Partitioner<Text, FlowBean> {
    
    	@Override
    	public int getPartition(Text key, FlowBean value, int numPartitions) {
    
    		// 1 获取电话号码的前三位
    		String preNum = key.toString().substring(0, 3);
    		
    		int partition = 4;
    		
    		// 2 判断是哪个省
    		if ("136".equals(preNum)) {
    			partition = 0;
    		}else if ("137".equals(preNum)) {
    			partition = 1;
    		}else if ("138".equals(preNum)) {
    			partition = 2;
    		}else if ("139".equals(preNum)) {
    			partition = 3;
    		}
    
    		return partition;
    	}
    }
    
  2. 在驱动函数中增加自定义数据分区设置和ReduceTask设置

    package com.atguigu.mapreduce.flowsum;
    import java.io.IOException;
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Job;
    import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
    import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
    
    public class FlowsumDriver {
    
    	public static void main(String[] args) throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException {
    
    		// 输入输出路径需要根据自己电脑上实际的输入输出路径设置
    		args = new String[]{"e:/output1","e:/output2"};
    
    		// 1 获取配置信息,或者job对象实例
    		Configuration configuration = new Configuration();
    		Job job = Job.getInstance(configuration);
    
    		// 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);
    
    		// 8 指定自定义数据分区
    		job.setPartitionerClass(ProvincePartitioner.class);
    		// 9 同时指定相应数量的reduce task
    		job.setNumReduceTasks(5);
    		
    		// 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);
    	}
    }
    

WritableComparable排序

  • 排序概述

  1. 排序的分类

  1. 自定义排序WritableComparable

    bean对象实现WritableComparable接口重写compareTo方法,就可以实现排序

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

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

  1. 需求

    根据上一章节Hadoop序列化之序列化案例实操产生的结果再次对总流量进行排序。

    1. 输入数据

      原始数据

      第一次处理后的数据

    2. 期望输出数据

      13509468723 7335 110349 117684

      13736230513 2481 24681 27162

      13956435636 132 1512 1644

      13846544121 264 0 264

      。。。 。。。

  2. 需求分析

  3. 代码实现

    1. FlowBean对象在在需求1基础上增加了比较功能

      package com.at编写Mapper类guigu.mapreduce.sort;
      import java.io.DataInput;
      import java.io.DataOutput;
      import java.io.IOException;
      import org.apache.hadoop.io.WritableComparable;
      
      public class FlowBean implements WritableComparable<FlowBean> {
      
      	private long upFlow;
      	private long downFlow;
      	private long sumFlow;
      
      	// 反序列化时,需要反射调用空参构造函数,所以必须有
      	public FlowBean() {
      		super();
      	}
      
      	public FlowBean(long upFlow, long downFlow) {
      		super();
      		this.upFlow = upFlow;
      		this.downFlow = downFlow;
      		this.sumFlow = upFlow + downFlow;
      	}
      
      	public void set(long upFlow, long downFlow) {
      		this.upFlow = upFlow;
      		this.downFlow = downFlow;
      		this.sumFlow = upFlow + downFlow;
      	}
      
      	public long getSumFlow() {
      		return sumFlow;
      	}
      
      	public void setSumFlow(long sumFlow) {
      		this.sumFlow = 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;
      	}
      
      	/**
      	 * 序列化方法
      	 * @param out
      	 * @throws IOException
      	 */
      	@Override
      	public void write(DataOutput out) throws IOException {
      		out.writeLong(upFlow);
      		out.writeLong(downFlow);
      		out.writeLong(sumFlow);
      	}
      
      	/**
      	 * 反序列化方法 注意反序列化的顺序和序列化的顺序完全一致
      	 * @param in
      	 * @throws IOException
      	 */
      	@Override
      	public void readFields(DataInput in) throws IOException {
      		upFlow = in.readLong();
      		downFlow = in.readLong();
      		sumFlow = in.readLong();
      	}
      
      	@Override
      	public String toString() {
      		return upFlow + "\t" + downFlow + "\t" + sumFlow;
      	}
      
      	@Override
      	public int compareTo(FlowBean o) {
      		// 倒序排列,从大到小
      		return this.sumFlow > o.getSumFlow() ? -1 : 1;
      	}
      }
      
    2. 编写Mapper类

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

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

      package com.atguigu.mapreduce.sort;
      import java.io.IOException;
      import org.apache.hadoop.conf.Configuration;
      import org.apache.hadoop.fs.Path;
      import org.apache.hadoop.io.Text;
      import org.apache.hadoop.mapreduce.Job;
      import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
      import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
      
      public class FlowCountSortDriver {
      
      	public static void main(String[] args) throws ClassNotFoundException, IOException, InterruptedException {
      
      		// 输入输出路径需要根据自己电脑上实际的输入输出路径设置
      		args = new String[]{"e:/output1","e:/output2"};
      
      		// 1 获取配置信息,或者job对象实例
      		Configuration configuration = new Configuration();
      		Job job = Job.getInstance(configuration);
      
      		// 6 指定本程序的jar包所在的本地路径
      		job.setJarByClass(FlowCountSortDriver.class);
      
      		// 2 指定本业务job要使用的mapper/Reducer业务类
      		job.setMapperClass(FlowCountSortMapper.class);
      		job.setReducerClass(FlowCountSortReducer.class);
      
      		// 3 指定mapper输出数据的kv类型
      		job.setMapOutputKeyClass(FlowBean.class);
      		job.setMapOutputValueClass(Text.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);
      	}
      }
      

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

  1. 需求

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

  2. 需求分析

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

  3. 案例实操

    1. 增加自定义分区类

      package com.atguigu.mapreduce.sort;
      import org.apache.hadoop.io.Text;
      import org.apache.hadoop.mapreduce.Partitioner;
      
      public class ProvincePartitioner extends Partitioner<FlowBean, Text> {
      
      	@Override
      	public int getPartition(FlowBean key, Text value, int numPartitions) {
      		
      		// 1 获取手机号码前三位
      		String preNum = value.toString().substring(0, 3);
      		
      		int partition = 4;
      		
      		// 2 根据手机号归属地设置分区
      		if ("136".equals(preNum)) {
      			partition = 0;
      		}else if ("137".equals(preNum)) {
      			partition = 1;
      		}else if ("138".equals(preNum)) {
      			partition = 2;
      		}else if ("139".equals(preNum)) {
      			partition = 3;
      		}
      
      		return partition;
      	}
      }
      
    2. 在驱动类中添加分区类

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

Combiner合并

(6)自定义Combiner实现步骤

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

    public class WordcountCombiner extends Reducer<Text, IntWritable, Text,IntWritable>{
    	@Override
    	protected void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {
    
            // 1 汇总操作
    		int count = 0;
    		for(IntWritable v :values){
    			count += v.get();
    		}
    
            // 2 写出
    		context.write(key, new IntWritable(count));
    	}
    }
    
  • 在Job驱动类中设置:

    job.setCombinerClass(WordcountCombiner.class);

Combiner合并案例实操

  1. 需求

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

    1. 数据输入

      banzhang ni hao

      xihuan hadoop banzhang

      banzhang ni hao

      xihuan hadoop banzhang

    2. 期望输出数据

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

  2. 需求分析

  3. 案例实操-方案一

    1. 增加一个WordcountCombiner类继承Reducer

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

      // 指定需要使用combiner,以及用哪个类作为combiner的逻辑
      job.setCombinerClass(WordcountCombiner.class);
      
  4. 案例实操-方案二

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

    • 使用后

GroupingComparator分组(辅助排序)

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

GroupingComparator分组案例实操

  1. 需求

    有如下订单数据

    订单id 商品id 成交金额
    0000001 Pdt_01 222.8
    Pdt_06 25.8
    0000002 Pdt_03 522.8
    Pdt_04 122.4
    Pdt_05 722.4
    0000003 Pdt_07 232.8
    Pdt_02 33.8

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

    1. 输入数据

      输入数据
      0000001 Pdt_01 222.8

      0000002 Pdt_06 722.4

      0000001 Pdt_05 25.8

      0000003 Pdt_01 232.8

      0000003 Pdt_01 33.8

      0000002 Pdt_03 522.8

      0000002 Pdt_04 122.4

    2. 期望输出数据

      1 222.8

      2 722.4

      3 232.8

  2. 需求分析

    1. 利用“订单id和成交金额”作为key,可以将Map阶段读取到的所有订单数据按照id分区,按照金额排序,发送到Reduce。

    2. 在Reduce端利用groupingComparator将订单id相同的kv聚合成组,然后取第一个即是最大值,如图所示。

  3. 代码实现

    1. 定义订单信息OrderBean类

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

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

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

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

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

ReduceTask工作机制

  1. ReduceTask工作机制

    ReduceTask工作机制,如图所示

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

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

    //默认值是1,手动设置为4
    job.setNumReduceTasks(4);
    
  3. 注意事项

  4. 实验:测试ReduceTask多少合适。

    1. 实验环境:1个Master节点,16个Slave节点:CPU:8GHZ,内存: 2G

    2. 实验结论:

      改变ReduceTask (数据量为1GB)

      Map task =16
      Reduce task 1 5 10 15 16 20 25 30 45 60
      总时间 892 146 110 92 88 100 128 101 145 104

OutputFormat数据输出

OutputFormat接口实现类

自定义OutputFormat

自定义OutputFormat案例实操

  1. 需求

    过滤输入的log日志,包含atguigu的网站输出到e:/atguigu.log,不包含atguigu的网站输出到e:/other.log。

    1. 输入数据

      http://www.baidu.com

      http://www.google.com

      http://cn.bing.com

      http://www.atguigu.com

      http://www.sohu.com

      http://www.sina.com

      http://www.sin2a.com

      http://www.sin2desa.com

      http://www.sindsafa.com

    2. 期望输出数据

      atguigu.log

      http://www.atguigu.com

      other.log

      http://cn.bing.com

      http://www.baidu.com

      http://www.google.com

      http://www.sin2a.com

      http://www.sin2desa.com

      http://www.sina.com

      http://www.sindsafa.com

      http://www.sohu.com

  2. 需求分析

  3. 案例实操

    1. 自定义一个OutputFormat类

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

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

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

      package com.atguigu.mapreduce.outputformat;
      import java.io.IOException;
      import org.apache.hadoop.io.NullWritable;
      import org.apache.hadoop.io.Text;
      import org.apache.hadoop.mapreduce.Reducer;
      
      public class FilterReducer extends Reducer<Text, NullWritable, Text, NullWritable> {
      
      	Text k = new Text();
      
      	@Override
      	protected void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException,InterruptedException {
      
      		String line = key.toString();
      		line = line + "\r\n";
      
             	k.set(line);
      
      		context.write(k, NullWritable.get());
      	}
      }
      
    5. 编写FilterDriver类

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

Join多种应用

Reduce Join工作原理及缺点

Reduce Join案例实操

  1. 需求

    order.txt

    id pid amount
    1001 01 1
    1002 02 2
    1003 03 3
    1004 01 4
    1005 02 5
    1006 03 6

    pd.txt

    pid pname
    01 小米
    02 华为
    03 格力

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

    最终数据形式

    id pname amount
    1001 小米 1
    1004 小米 4
    1002 华为 2
    1005 华为 5
    1003 格力 3
    1006 格力 6
  2. 需求分析

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

  3. 代码实现

    1. 创建商品和订合并后的Bean类

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

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

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

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

    运行程序查看结果

    1001 小米 1

    1001 小米 1

    1002 华为 2

    1002 华为 2

    1003 格力 3

    1003 格力 3

  5. 总结

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

    解决方案:Map端实现数据合并

Map Join

  1. 使用场景

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

  2. 优点

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

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

  3. 具体办法:采用DistributedCache

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

    2. 在驱动函数中加载缓存。

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

Map Join案例实操

  1. 需求

    order.txt

    id pid amount
    1001 01 1
    1002 02 2
    1003 03 3
    1004 01 4
    1005 02 5
    1006 03 6

    pd.txt

    pid pname
    01 小米
    02 华为
    03 格力

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

    id pname amount
    1001 小米 1
    1004 小米 4
    1002 华为 2
    1005 华为 5
    1003 格力 3
    1006 格力 6
  2. 需求分析

    MapJoin适用于关联表中有小表的情形;

  3. 实现代码

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

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

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

计数器应用

数据清洗(ETL)

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

数据清洗案例实操-简单解析版

  1. 需求

    去除日志中字段长度小于等于11的日志。

    1. 输入数据

      • 内容太多,就不在此粘贴了,大家可自行创建测试数据

    2. 期望输出数据

      每行字段长度都大于11。

  2. 需求分析

    ​ 需要在Map阶段对输入的数据根据规则进行过滤清洗。

  3. 实现代码

    1. 编写LogMapper类

      package com.atguigu.mapreduce.weblog;
      import java.io.IOException;
      import org.apache.hadoop.io.LongWritable;
      import org.apache.hadoop.io.NullWritable;
      import org.apache.hadoop.io.Text;
      import org.apache.hadoop.mapreduce.Mapper;
      
      public class LogMapper extends Mapper<LongWritable, Text, Text, NullWritable>{
      	
      	Text k = new Text();
      	
      	@Override
      	protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
      		
      		// 1 获取1行数据
      		String line = value.toString();
      		
      		// 2 解析日志
      		boolean result = parseLog(line,context);
      		
      		// 3 日志不合法退出
      		if (!result) {
      			return;
      		}
      		
      		// 4 设置key
      		k.set(line);
      		
      		// 5 写出数据
      		context.write(k, NullWritable.get());
      	}
      
      	// 2 解析日志
      	private boolean parseLog(String line, Context context) {
      
      		// 1 截取
      		String[] fields = line.split(" ");
      		
      		// 2 日志长度大于11的为合法
      		if (fields.length > 11) {
      
      			// 系统计数器
      			context.getCounter("map", "true").increment(1);
      			return true;
      		}else {
      			context.getCounter("map", "false").increment(1);
      			return false;
      		}
      	}
      }
      
    2. 编写LogDriver类

      package com.atguigu.mapreduce.weblog;
      import org.apache.hadoop.conf.Configuration;
      import org.apache.hadoop.fs.Path;
      import org.apache.hadoop.io.NullWritable;
      import org.apache.hadoop.io.Text;
      import org.apache.hadoop.mapreduce.Job;
      import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
      import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
      
      public class LogDriver {
      
      	public static void main(String[] args) throws Exception {
      
      		// 输入输出路径需要根据自己电脑上实际的输入输出路径设置
              args = new String[] { "e:/input/inputlog", "e:/output1" };
      
      		// 1 获取job信息
      		Configuration conf = new Configuration();
      		Job job = Job.getInstance(conf);
      
      		// 2 加载jar包
      		job.setJarByClass(LogDriver.class);
      
      		// 3 关联map
      		job.setMapperClass(LogMapper.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 提交
      		job.waitForCompletion(true);
      	}
      }
      

数据清洗案例实操-复杂解析版

  1. 需求

    对Web访问日志中的各字段识别切分,去除日志中不合法的记录。根据清洗规则,输出过滤后的数据。

  2. 实现代码

    1. 定义一个bean,用来记录日志数据中的各数据字段

      package com.atguigu.mapreduce.log;
      
      public class LogBean {
      	private String remote_addr;// 记录客户端的ip地址
      	private String remote_user;// 记录客户端用户名称,忽略属性"-"
      	private String time_local;// 记录访问时间与时区
      	private String request;// 记录请求的url与http协议
      	private String status;// 记录请求状态;成功是200
      	private String body_bytes_sent;// 记录发送给客户端文件主体内容大小
      	private String http_referer;// 用来记录从那个页面链接访问过来的
      	private String http_user_agent;// 记录客户浏览器的相关信息
      	private boolean valid = true;// 判断数据是否合法
      
      	public String getRemote_addr() {
      		return remote_addr;
      	}
      
      	public void setRemote_addr(String remote_addr) {
      		this.remote_addr = remote_addr;
      	}
      
      	public String getRemote_user() {
      		return remote_user;
      	}
      
      	public void setRemote_user(String remote_user) {
      		this.remote_user = remote_user;
      	}
      
      	public String getTime_local() {
      		return time_local;
      	}
      
      	public void setTime_local(String time_local) {
      		this.time_local = time_local;
      	}
      
      	public String getRequest() {
      		return request;
      	}
      
      	public void setRequest(String request) {
      		this.request = request;
      	}
      
      	public String getStatus() {
      		return status;
      	}
      
      	public void setStatus(String status) {
      		this.status = status;
      	}
      
      	public String getBody_bytes_sent() {
      		return body_bytes_sent;
      	}
      
      	public void setBody_bytes_sent(String body_bytes_sent) {
      		this.body_bytes_sent = body_bytes_sent;
      	}
      
      	public String getHttp_referer() {
      		return http_referer;
      	}
      
      	public void setHttp_referer(String http_referer) {
      		this.http_referer = http_referer;
      	}
      
      	public String getHttp_user_agent() {
      		return http_user_agent;
      	}
      
      	public void setHttp_user_agent(String http_user_agent) {
      		this.http_user_agent = http_user_agent;
      	}
      
      	public boolean isValid() {
      		return valid;
      	}
      
      	public void setValid(boolean valid) {
      		this.valid = valid;
      	}
      
      	@Override
      	public String toString() {
      		StringBuilder sb = new StringBuilder();
      		sb.append(this.valid);
      		sb.append("\001").append(this.remote_addr);
      		sb.append("\001").append(this.remote_user);
      		sb.append("\001").append(this.time_local);
      		sb.append("\001").append(this.request);
      		sb.append("\001").append(this.status);
      		sb.append("\001").append(this.body_bytes_sent);
      		sb.append("\001").append(this.http_referer);
      		sb.append("\001").append(this.http_user_agent);
      		
      		return sb.toString();
      	}
      }
      
    2. 编写LogMapper类

      package com.atguigu.mapreduce.log;
      import java.io.IOException;
      import org.apache.hadoop.io.LongWritable;
      import org.apache.hadoop.io.NullWritable;
      import org.apache.hadoop.io.Text;
      import org.apache.hadoop.mapreduce.Mapper;
      
      public class LogMapper extends Mapper<LongWritable, Text, Text, NullWritable>{
      	Text k = new Text();
      	
      	@Override
      	protected void map(LongWritable key, Text value, Context context)	throws IOException, InterruptedException {
      
      		// 1 获取1行
      		String line = value.toString();
      		
      		// 2 解析日志是否合法
      		LogBean bean = pressLog(line);
      		
      		if (!bean.isValid()) {
      			return;
      		}
      		
      		k.set(bean.toString());
      		
      		// 3 输出
      		context.write(k, NullWritable.get());
      	}
      
      	// 解析日志
      	private LogBean pressLog(String line) {
      
      		LogBean logBean = new LogBean();
      		
      		// 1 截取
      		String[] fields = line.split(" ");
      		
      		if (fields.length > 11) {
      
      			// 2封装数据
      			logBean.setRemote_addr(fields[0]);
      			logBean.setRemote_user(fields[1]);
      			logBean.setTime_local(fields[3].substring(1));
      			logBean.setRequest(fields[6]);
      			logBean.setStatus(fields[8]);
      			logBean.setBody_bytes_sent(fields[9]);
      			logBean.setHttp_referer(fields[10]);
      			
      			if (fields.length > 12) {
      				logBean.setHttp_user_agent(fields[11] + " "+ fields[12]);
      			}else {
      				logBean.setHttp_user_agent(fields[11]);
      			}
      			
      			// 大于400,HTTP错误
      			if (Integer.parseInt(logBean.getStatus()) >= 400) {
      				logBean.setValid(false);
      			}
      		}else {
      			logBean.setValid(false);
      		}
      		
      		return logBean;
      	}
      }
      
    3. 编写LogDriver类

      package com.atguigu.mapreduce.log;
      import org.apache.hadoop.conf.Configuration;
      import org.apache.hadoop.fs.Path;
      import org.apache.hadoop.io.NullWritable;
      import org.apache.hadoop.io.Text;
      import org.apache.hadoop.mapreduce.Job;
      import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
      import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
      
      public class LogDriver {
      	public static void main(String[] args) throws Exception {
      		
      		// 1 获取job信息
      		Configuration conf = new Configuration();
      		Job job = Job.getInstance(conf);
      
      		// 2 加载jar包
      		job.setJarByClass(LogDriver.class);
      
      		// 3 关联map
      		job.setMapperClass(LogMapper.class);
      
      		// 4 设置最终输出类型
      		job.setOutputKeyClass(Text.class);
      		job.setOutputValueClass(NullWritable.class);
      
      		// 5 设置输入和输出路径
      		FileInputFormat.setInputPaths(job, new Path(args[0]));
      		FileOutputFormat.setOutputPath(job, new Path(args[1]));
      
      		// 6 提交
      		job.waitForCompletion(true);
      	}
      }
      

MapReduce开发总结(重点)

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


由于篇幅过长,[Hadoop数据压缩]等以后的内容,请看下回分解!

posted @ 2020-07-23 16:05  假装文艺范儿  阅读(165)  评论(0编辑  收藏  举报