MapReduce 學習3-------讀取輸入文件


1. map任務處理
1.1 讀取輸入文件內容,解析成key、value對。對輸入文件的每一行,解析成key、value對。每一個鍵值對調用一次map函數。
wcjob.setInputFormatClass(TextInputFormat.class);

InputFormat接口提供了兩個方法來實現MapReduce數據源的輸入

1.1.1 把輸入文件切分成一個一個InputSplit,然后每一個InputSplit分配給一個獨立的mapper任務進行處理,InputSplit就是包含輸入文件的內容信息

public abstract List<InputSplit> getSplits(JobContext context);

 

FileInputFormat:


public List<InputSplit> getSplits(JobContext job) throws IOException {
   //獲取塊的最少大小
    long minSize = Math.max(getFormatMinSplitSize(), getMinSplitSize(job));
//獲取塊的最大的size,默認是long.maxvalue
    long maxSize = getMaxSplitSize(job);

  
    List<InputSplit> splits = new ArrayList<InputSplit>();
//獲取輸入文件的相關文件信息
    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;
      //循環切分文件makeSplit(length-bytesRemaining//起始偏移量,splitSize//切片大小),
/**
*如文件大小為500M,切分大小為128M,那么循環makeSplit
*1.makeSplit(128M,128M)
*2.makeSplit(256M,128M)
*3.makeSplit(384M,128M)
*循環切成3個InputSplit */
          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;
          }

          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
          splits.add(makeSplit(path, 0, length, blkLocations[0].getHosts(),
                      blkLocations[0].getCachedHosts()));
        }
      } else {
        //Create empty hosts array for zero length files
        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.elapsedMillis());
    }
    return splits;
  }

 

1.1.2 提供一個RecordReader的實現類,把InputSplit的內容一行一行地拆分成<k,v>

public abstract  RecordReader<K,V> createRecordReader(InputSplit split,TaskAttemptContext context);

public RecordReader<LongWritable, Text> 
    createRecordReader(InputSplit split,
                       TaskAttemptContext context) {
    String delimiter = context.getConfiguration().get(
        "textinputformat.record.delimiter");
    byte[] recordDelimiterBytes = null;
    if (null != delimiter)
      recordDelimiterBytes = delimiter.getBytes(Charsets.UTF_8);
    return new LineRecordReader(recordDelimiterBytes);
}


public class LineRecordReader extends RecordReader<LongWritable, Text> {

  //判斷Inputsplit是否有下一行內容,並且讀取這一行內容
  public boolean nextKeyValue() throws IOException {
    if (key == null) {
      key = new LongWritable();
    }
    key.set(pos);
    if (value == null) {
      value = new Text();
    }
    int newSize = 0;
    // We always read one extra line, which lies outside the upper
    // split limit i.e. (end - 1)
    while (getFilePosition() <= end || in.needAdditionalRecordAfterSplit()) {
      if (pos == 0) {
        newSize = skipUtfByteOrderMark();
      } else {
        newSize = in.readLine(value, maxLineLength, maxBytesToConsume(pos));
        pos += newSize;
      }

      if ((newSize == 0) || (newSize < maxLineLength)) {
        break;
      }

      // line too long. try again
      LOG.info("Skipped line of size " + newSize + " at pos " + 
               (pos - newSize));
    }
    if (newSize == 0) {
      key = null;
      value = null;
      return false;
    } else {
      return true;
    }
  }   

  //每讀取一行要先把這一行的key,value值取出去,不然每次調用nextKeyValue()都把值覆蓋
  public LongWritable getCurrentKey() {
    return key;
  }

  public Text getCurrentValue() {
    return value;
  }


}

 

在mapper端是怎么調用RecordReader方法

public class Mapper<KEYIN, VALUEIN, KEYOUT, VALUEOUT> {
  。。。。
  public abstract class Context
    implements MapContext<KEYIN,VALUEIN,KEYOUT,VALUEOUT> {
  }

  public void run(Context context) throws IOException, InterruptedException {
    setup(context);
    try {
      //循序讀取Inputsplit每一行的內容,每讀一行調用一次map函數
      while (context.nextKeyValue()) {
        map(context.getCurrentKey(), context.getCurrentValue(), context);
      }
    } finally {
      當完成讀取一個Inputsplit時,就調用這個cleanup函數
      cleanup(context);
    }
  }
  。。。。
}


public class MapContextImpl<KEYIN,VALUEIN,KEYOUT,VALUEOUT> 
    extends TaskInputOutputContextImpl<KEYIN,VALUEIN,KEYOUT,VALUEOUT> 
    implements MapContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT> {

    private RecordReader<KEYIN,VALUEIN> reader;

    public KEYIN getCurrentKey() throws IOException, InterruptedException {
      return reader.getCurrentKey();
    }


  public VALUEIN getCurrentValue() throws IOException, InterruptedException {
    return reader.getCurrentValue();
  }


  public boolean nextKeyValue() throws IOException, InterruptedException {
    return reader.nextKeyValue();
  }
}

context.nextKeyValue() 就是 reader.nextKeyValue();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM