Hadoop学习——(MapReduce数据共享) 2.x后DistributedCache无法使用替代方案

论坛 期权论坛 脚本     
匿名网站用户   2020-12-20 10:36   22   0

1. 简介

DistributedCache是MapReduce程序中不同task之间共享数据的一种方式,即——

  • 将job指定的文件,在job执行前,先行分发到task执行的机器上
  • 之后的MR task读取缓存文件,即可实现不同task之间的数据共享

这个文件需要事先放在hdfs上,且只能读取不能修改。

2. 替代方案

在Hadoop2.x之后的版本,导入DistributedCache如下,会提示这个包已经被丢弃,无法使用了。

在这里插入图片描述

Hadoop2.x中也提供了其他API可以实现相同的功能,如下:

  1. 在main函数中——
job.addCacheFile(new Path(centers).toUri());
  1. 在map或reduce的setup函数中——
public void setup(Context context) throws IOException,InterruptedException{
    Configuration conf = context.getConfiguration();
    URI localCacheFile = context.getCacheFiles()[0]; //GET THE URI
    BufferedReader reader = new BufferedReader(new InputStreamReader(
        FileSystem.get(conf).open(new Path(localCacheFile.getPath()))));
    /*处理文件,比如下面是读到类成员变量lines里面,在mapper类我先定义了lines=“”*/
    String line;
    while ((line = reader.readLine()) != null) { lines += line + "-->"; }
    reader.close();
}

这样就可以在map函数中使用达到共享数据的效果。

3. 关于网上看到的解决方案

在查阅该问题的时候,看到一些博客,如参考文献[2]提供的方法,在读取文件时是直接使用FileReader,如下:

BufferedReader reader = new BufferedReader(new FileReader(cacheFileURI.getPath()));
  String line;
  while ((line = reader.readLine()) != null) {...}
  reader.close();

但是使用这种方法似乎访问的是本地的文件,而不是hdfs的文件,所以我使用的时候会提示“找不到文件”。

Reference

  1. DistributedCache小记

  2. Hadoop 2.x的DistributedCache无法工作的问题

  3. Hadoop DistributedCache is deprecated - what is the preferred API?

  4. MapReduce读文件

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP