1. 简介
DistributedCache是MapReduce程序中不同task之间共享数据的一种方式,即——
- 将job指定的文件,在job执行前,先行分发到task执行的机器上
- 之后的MR task读取缓存文件,即可实现不同task之间的数据共享
这个文件需要事先放在hdfs上,且只能读取不能修改。
2. 替代方案
在Hadoop2.x之后的版本,导入DistributedCache如下,会提示这个包已经被丢弃,无法使用了。

Hadoop2.x中也提供了其他API可以实现相同的功能,如下:
- 在main函数中——
job.addCacheFile(new Path(centers).toUri());
- 在map或reduce的setup函数中——
public void setup(Context context) throws IOException,InterruptedException{
Configuration conf = context.getConfiguration();
URI localCacheFile = context.getCacheFiles()[0];
BufferedReader reader = new BufferedReader(new InputStreamReader(
FileSystem.get(conf).open(new Path(localCacheFile.getPath()))));
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
-
DistributedCache小记
-
Hadoop 2.x的DistributedCache无法工作的问题
-
Hadoop DistributedCache is deprecated - what is the preferred API?
-
MapReduce读文件
|