(1) 通过 Configuration 来传递参数
在main函数中调用set方法设置参数,
在mapper/reducer中通过上下文context来获取当前作业的配置, 并获取参数,
注: context 很有用, 能获取当前作业的大量信息,例如上面就获取了任务ID
job.java的main函数中
Configuration configuration = new Configuration();
configuration.set("lastUpdateTime",args[2]);
mapper/reducer.java的map/reduce函数中
Configuration conf = context.getConfiguration();
String lastUpdateTime = conf.get("lastUpdateTime");
自动化脚本中
hadoop jar ~/Desktop/cjb/cjbjobs/cjb_job1.jar /cjb1/data /cjb1/cjb_job1_result 3
(2)使用DistributedCache
背景:
在使用mapreduce时,各个map之间需要共享一些信息。如果信息不大,可以保存在conf中(如上)。但是需求是在各个map之间共享文件或者tar包
使用distributedCache可以满足这个需求:
distributedCache可以把HDFS上的文件(数据文件、压缩文件等等)分发到各个执行task的节点。执行map或者reduce task的节点就可以在本地,直接用java的IO接口读取这些文件。
有两个需要注意的地方:
被分发的文件需要事先存储在hdfs上;
这些文件是只读的。
使用distributedCache的步骤:
1、在conf里正确配置被分发的文件的路径(hdfs上的路径)
2、在自定义的mapper或reducer中获取文件下载到本地后的路径(linux文件系统路径);一般是重写configure或者重写setup(新方式)
3、在自定义的mapper或reducer类中读取这些文件的内容
distributedCache还提供创建符号链接的功能,第2步就不需要获取文件在本地的路径,直接使用约定的符号链接即可。
分发的文件大致分两种类型:文件;压缩包
job.java的main函数中
configuration = new Configuration();
DistributedCache.createSymlink(configuration);
String thirdparas = args[2];
Path paraspath = new Path(thirdparas);
String uriWithLink = paraspath.toUri().toString() + "#" + "paraspath";
DistributedCache.addCacheFile(new URI(uriWithLink), configuration);
mapper/reducer.java的map/reduce函数中
StringBuffer paras = new StringBuffer();
public void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
if (context.getCacheFiles() != null && context.getCacheFiles().length > 0) {
String path = context.getLocalCacheFiles()[0].getName();
File itermOccurrenceMatrix = new File(path);
FileReader fileReader = new FileReader(itermOccurrenceMatrix);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String s;
while ((s = bufferedReader.readLine()) != null) {
paras.append(s);
}
bufferedReader.close();
fileReader.close();
}
}
自动化脚本中
hadoop jar ~/Desktop/model/modeljobs/m_job1.jar /model/data /model/m_job1_result /model/parasmatrix