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 {  

            //使用从缓存文件中读取的数据  

                        //....  

                        //....  

                } 

 }  

猜你喜欢

转载自blog.csdn.net/twj0823/article/details/84445457
今日推荐