MR中实现参数传递/数据共享

 

(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 

 

转载于:https://my.oschina.net/MasterLi161307040026/blog/1549049

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值