1. 程式人生 > >MapReduce系列之全域性引數、資料檔案的傳遞與引用

MapReduce系列之全域性引數、資料檔案的傳遞與引用

MapReduce程式設計過程中全域性引數、資料檔案的傳遞與引用的主要有一下幾種方法。

1、讀寫HDFS檔案

通過利用Hadoop的Java Apl來實現讀寫HDFS檔案,需要注意的是針對多個Map或Reduce的寫操作會產生衝突,覆蓋原有資料

優點:能夠實現讀寫,也比較直觀

缺點:要共享一些很小的全域性資料也需要I/O,將佔用系統資源,增加作業完成的資源消耗

2、配置Job屬性

在MapReduce執行過程中task可以讀取job屬性。基於此,可以在任務啟動之初利用Configuration類中的set(String name,String value)將一些簡單的全域性資料封裝到作業的配置屬性中,然後在task中利用

Context.getConfiguration( ).get(String name)獲取配置到屬性中的全域性資料。

優點:簡單,資源消耗少

缺點:對大量的共享資料比較無力

3、在Job中進行配置:

job.addArchiveToClassPath(archive);  //快取jar包到task執行節點的classpath中

job.addCacheArchive(uri);   //快取壓縮包檔案到task執行節點的工作目錄

job.addCacheFile(uri);  //快取普通檔案到task執行節點的工作目錄

job.addFileToClassPath(file);  //快取普通檔案到task執行節點的classpath中

在Mapper或Reducer中通過Context進行獲取

@Override

protected void setup(Mapper<LongWritable, Text, Text, Text>.Context context)

throws IOException, InterruptedException {

    context.getArchiveClassPaths();

    context.getCacheArchives();

    context.getCacheFiles();

    context.getFileClassPaths();

FileSplit split = (FileSplit)context.getInputSplit();

}

4、使用DistributedCache

DistributedCache是MapReduce中為應用提供快取檔案的只讀工具,可以快取文字檔案、壓縮檔案和jar檔案等。

優點:每個job共享檔案只會在啟動之後複製一次,並且適用於大量的共享資料

缺點:它是隻讀的

如何使用:

1)將要快取的檔案複製到HDFS上  

$ bin/hadoop fs -copyFromLocal localpath hdfspath  

2)啟用作業的屬性配置,並設定待快取檔案  

Configuration conf = new  Configuration();  

DistributedCache.addCacheFile(new URI(hdfsPath),conf); 

3)在Map中使用DistributedCache  

public static class LocalMap extends Mapper<Object, Text, Text, Text> {  

        private Path[] localArchives;  

        private Path[] localFiles;  

        @Override  

        protected void setup(Mapper<Object, Text, Text, Text>.Context context)  

                throws IOException, InterruptedException {  

                        //獲取快取檔案  

                        Configuration conf = context.getConfiguration();  

            localArchives = DistributedCache.getLocalCacheArchives(conf);  

            localFiles = DistributedCache.getLocalCacheFiles(conf);  

        }  

        @Override  

        protected void map(Object key, Text value, Mapper<Object, Text, Text, Text>.Context context)  

                throws IOException, InterruptedException {  

            //使用從快取檔案中讀取的資料  

                        //....  

                        //....  

                } 

 }