MapReduce從輸入檔案到Mapper處理之間的過程

來源:互聯網
上載者:User

標籤:style   blog   io   ar   color   os   使用   sp   for   

1、MapReduce代碼入口

FileInputFormat.setInputPaths(job, new Path(input)); //設定MapReduce輸入格式job.waitForCompletion(true);

2、InputFormat分析

public abstract class InputFormat<K, V> {    //擷取輸入檔案的分區,僅是邏輯分區,並沒有物理分區    public abstract  List<InputSplit> getSplits(JobContext context);        //建立RecordReader,從InputSplit中讀取資料    public abstract  RecordReader<K,V> createRecordReader(InputSplit split,TaskAttemptContext context) ;}

不同的InputFormat會各自實現不同的檔案讀取方式以及分區方式,每個輸入分區(InputSplit)會被單獨的map task作為資料來源

3、InputSplit

Mapper的輸入是一個一個的輸入分區(InputSplit)

public abstract class InputSplit {  public abstract long getLength();  public abstract String[] getLocations();}public class FileSplit extends InputSplit implements Writable{    private Path file; //檔案路徑    private long start; //分區起始位置    private long length;  //分區長度    private String[] hosts; //儲存分區的hosts        public FileSplit(Path file, long start, long length, String[] hosts) {        this.file = file;        this.start = start;        this.length = length;        this.hosts = hosts;    }}

一個FileSplit對應Mapper的一個輸入檔案,不管這個檔案有多麼的小,也是作為一個單獨的InputSplit來處理;
在輸入檔案是由大量小檔案組成的情境下,就會有大量的InputSplit,從而需要大量的Mapper的處理;
大量的Mapper Task建立和銷毀開銷將是巨大的;可以採用CombineFileSplit將多個小檔案進行合并再交由Mapper Task處理;

4、FileInputFormat

public List<InputSplit> getSplits(JobContext job) throws IOException {    /**     * getFormatMinSplitSize() = 1     * job.getConfiguration().getLong(SPLIT_MINSIZE, 1L)     * SPLIT_MINSIZE = "mapreduce.input.fileinputformat.split.minsize"     * mapred-default.xml中參數為0     */    long minSize = Math.max(getFormatMinSplitSize(), getMinSplitSize(job)); //計算分區的最小值: max(1,0) = 1        /**     * SPLIT_MAXSIZE = "mapreduce.input.fileinputformat.split.maxsize"     * mapred-default.xml中參數為空白     */    long maxSize = getMaxSplitSize(job); //計算分區的最大值:Long.MAX_VALUE       //儲存輸入檔案的分區結果    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) {            ...            if (isSplitable(job, path)) { //能分區                long blockSize = file.getBlockSize();                long splitSize = computeSplitSize(blockSize, minSize, maxSize);{                    //max(1, min(Long.MAX_VALUE, 64M)) = 64M 預設情況下splitSize=blockSize                    return Math.max(minSize, Math.min(maxSize, blockSize));                 }                //迴圈分區,當剩餘資料與分區大小比值大於Split_Slop時,繼續分區,小於等於時,停止分區                long bytesRemaining = length;                while (((double) bytesRemaining)/splitSize > SPLIT_SLOP) { //SPLIT_SLOP = 1.1                    int blkIndex = getBlockIndex(blkLocations, length-bytesRemaining);                    splits.add(makeSplit(path, length-bytesRemaining, splitSize, blkLocations[blkIndex].getHosts()));                    bytesRemaining -= splitSize;                }                //處理餘下的資料                if (bytesRemaining != 0) {                    int blkIndex = getBlockIndex(blkLocations, length-bytesRemaining);                    splits.add(makeSplit(path, length-bytesRemaining, bytesRemaining, blkLocations[blkIndex].getHosts()));                }            } else { // 不可分區,整塊返回(有些壓縮後是不能分區處理的)                splits.add(makeSplit(path, 0, length, blkLocations[0].getHosts()));            }        } else {             splits.add(makeSplit(path, 0, length, new String[0]));        }    }    job.getConfiguration().setLong(NUM_INPUT_FILES, files.size()); // 設定輸入檔案數量    LOG.debug("Total # of splits: " + splits.size());    return splits;}

5、PathFilter

protected List<FileStatus> listStatus(JobContext job) throws IOException {    ......    List<PathFilter> filters = new ArrayList<PathFilter>();    filters.add(hiddenFileFilter);    PathFilter jobFilter = getInputPathFilter(job);    if (jobFilter != null) {      filters.add(jobFilter);    }    PathFilter inputFilter = new MultiPathFilter(filters);    ......}

PathFilter檔案篩選器介面,使用它我們可以控制哪些檔案要作為輸入,哪些不作為輸入;
PathFilter有一個accept(Path)方法,當接收的Path要被包含進來,就返回true,否則返回false;

public interface PathFilter {    boolean accept(Path path);}//過濾掉檔案名稱以_或者.開頭的檔案private static final PathFilter hiddenFileFilter = new PathFilter(){    public boolean accept(Path p){        String name = p.getName();         return !name.startsWith("_") && !name.startsWith(".");     }}; 

6、RecordReader

RecordReader將InputSplit拆分成KEY-VALUE對

public abstract class RecordReader<KEYIN, VALUEIN> implements Closeable {    //InputSplit初始化    public abstract void initialize(InputSplit split,TaskAttemptContext context) ;        //讀取分區下一個<key, value>對    public abstract boolean nextKeyValue() throws IOException, InterruptedException;        //獲得當前讀取到的KEY    public abstract KEYIN getCurrentKey() throws IOException, InterruptedException;        //獲得當前讀取到的VALUE     public abstract  VALUEIN getCurrentValue() throws IOException, InterruptedException;        //跟蹤讀取分區的進度    public abstract float getProgress() throws IOException, InterruptedException;        //關閉RecordReader    public abstract void close() throws IOException;}

7、Mapper

public class Mapper<KEYIN, VALUEIN, KEYOUT, VALUEOUT> {    public abstract class Context implements MapContext<KEYIN,VALUEIN,KEYOUT,VALUEOUT> {    }      //預先處理,僅在map task啟動時運行一次    protected void setup(Context context) throws IOException, InterruptedException {    }    //對於InputSplit中的每一對<key, value>都會運行一次    protected void map(KEYIN key, VALUEIN value, Context context) throws IOException, InterruptedException {        context.write((KEYOUT) key, (VALUEOUT) value);    }    //掃尾工作,比如關閉流等    protected void cleanup(Context context) throws IOException, InterruptedException {    }      public void run(Context context) throws IOException, InterruptedException {        setup(context);        try {            while (context.nextKeyValue()) {                map(context.getCurrentKey(), context.getCurrentValue(), context);            }        } finally {            cleanup(context);        }    }}

模板模式的應用:run方法:
1)setup
2)迴圈從InputSplit中獲得到的KV對調用map函數進行處理
3)cleanup

 

至此完成了MapReduce的輸入檔案是如何被過濾、分區、讀取、讀出“K-V對”,然後交給Mapper類來處理

 

MapReduce從輸入檔案到Mapper處理之間的過程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.