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

本文详细介绍了在Hadoop 2.x环境中使用DistributedCache API的变化及遇到的问题。包括新旧API的对比、如何正确加载HDFS文件作为缓存、以及当mapper中无法获取到缓存文件时的解决办法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://www.codelast.com/

现象:和这个帖子描述的一样,简单说来就是,在Hadoop 2.x上,用新的DistributedCache的API,在mapper中会获取不到这个cache文件。
下面就详细地描述一下新旧API的用法区别以及解决办法。

『1』旧API
将HDFS文件添加到distributed cache中:

Configuration conf = job.getConfiguration();
DistributedCache.addCacheFile(newURI(inputFileOnHDFS), conf);  // add file to distributed cache

其中,inputFileOnHDFS是一个HDFS文件的路径,也就是你要用作distribute cache的文件的路径,例如 /user/codelast/123.txt
在mapper的setup()方法中:

Configuration conf = context.getConfiguration();
Path[] localCacheFiles = DistributedCache.getLocalCacheFiles(conf);
readCacheFile(localCacheFiles[0]);

其中,readCacheFile()是我们自己的读取cache文件的方法,可能是这样做的(仅举个例子):

private static void readCacheFile(Path cacheFilePath)throwsIOException {
  BufferedReader reader =newBufferedReader(newFileReader(cacheFilePath.toUri().getPath()));
  String line;
  while((line = reader.readLine()) !=null) {
    //TODO: your code here
  }
  reader.close();
}


文章来源:http://www.codelast.com/
『2』新API
上面的代码中,addCacheFile() 方法和 getLocalCacheFiles() 都已经被Hadoop 2.x标记为 @Deprecated了。
因此,有一套新的API来实现同样的功能,这个链接里有示例,我在这里再详细地写一下。
将HDFS文件添加到distributed cache中:

job.addCacheFile(newPath(inputFileOnHDFS).toUri());


在mapper的setup()方法中:

Configuration conf = context.getConfiguration();
URI[] localCacheFiles = context.getCacheFiles();
readCacheFile(localCacheFiles[0]);


其中,readCacheFile()是我们自己的读取cache文件的方法,可能是这样做的(仅举个例子):

private static void readCacheFile(URI cacheFileURI)throwsIOException {
  BufferedReader reader =newBufferedReader(newFileReader(cacheFileURI.getPath()));
  String line;
  while((line = reader.readLine()) !=null) {
    //TODO: your code here
  }
  reader.close();
}



但是就像文章开头的那个链接里所描述的问题一样,你可能会发现 context.getCacheFiles() 总是返回null,也就是你无法读到cache文件。
这个问题有可能是 这个bug造成的,你可以对比一下你的Hadoop版本。
文章来源: http://www.codelast.com/
『3』解决办法
(1)打patch
(2)升级Hadoop版本
(3)使用旧的DistributedCache API,经测试OK
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值