hadoop的DistributedCache

DistributedCache类主要用来设定文件,jar等。其的思想就是将指定的文件(必须在hdfs文件系统上面)在每一个task运行的地方都复制一份数据,所以在map或reduce函数中读取DistributedCache设定的文件就可以在每一个task运行上的机器本地读取,而不用再走网络了。
下面是一个例子:
1.jobRun里面
 JobConf jobConf = new JobConf(xxx.class);
  DistributedCache.createSymlink(jobConf);//这个地方设定才会成功
  String path = args[3];//path的路径要像:/lll/llx  或 lll/llx(此处是相对路径,不要./lll/llx然后用new URI(path),这样会导致map或reduce函数中找不到文件)
  Path filePath = new Path(path);//为hadoop中的类
  String uriWithLink = filePath.toUri().toString() + "#" + "ex.txt";//uri非常重要,否则会发生文件找不到的情况
  System.out.println("uriWithLink:" + uriWithLink);
  try {
   DistributedCache.addCacheFile(new URI(uriWithLink), jobConf);
  } catch (URISyntaxException e) {
   e.printStackTrace();
  }

2.map或reduce里面
  FileReader fr = new FileReader(cacheFile);//cacheFile="ex.txt"
  BufferedReader bf = new BufferedReader(fr);
  String line = null ;
  while( (line = bf.readLine() ) != null){
   System.out.println(line);
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章