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 {  

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

                        //....  

                        //....  

                } 

 }  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值