《Hadoop实战》读书笔记=========MapReduce Job中全局共享数据
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、使用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 {
//使用从缓存文件中读取的数据
//....
//....
}
}