MapReduce-使用NLineInputFormat处理大文件-求文件奇偶数行之和

在上一篇《 MapReduce-定制Partitioner-求文件奇偶数行之和》博客中有朋友提到“如果文件很大,就被分成了多个record,那么每个record中的文件的奇数和偶数相对于原来的文件来说,就不确定了”这样一个问题,这一篇文章就对这种情况的处理进行说明一下,解决的思路如下:
我们只要固定每一个inputSplit的行数,我们就可以确定某一个inputSplit的某一行在整个文件中是奇数行还是偶数行。而且mapreduce框架已经为我们提供了NLineInputFormat来处理这一个问题,我们只用在启动程序中加入两行代码就能解决这个问题。
处理数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
这里我们假设数据很大被分成了两个split,我们的启动程序如下:

其于的map端代码,reduce端代码完全以及partition的代码没有任何改动,参见《MapReduce-定制Partitioner-求文件奇偶数行之和

  1. import org.apache.hadoop.conf.Configuration;  
  2. import org.apache.hadoop.fs.FileSystem;  
  3. import org.apache.hadoop.fs.Path;  
  4. import org.apache.hadoop.io.IntWritable;  
  5. import org.apache.hadoop.io.LongWritable;  
  6. import org.apache.hadoop.io.Text;  
  7. import org.apache.hadoop.mapreduce.Job;  
  8. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;  
  9. import org.apache.hadoop.mapreduce.lib.input.NLineInputFormat;  
  10. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;  
  11.   
  12. public class JobMain {  
  13.     public static void main(String[] args) throws Exception {  
  14.         Configuration configuration = new Configuration();  
  15.         /** 
  16.          * 对比前一篇博客的启动程序多了以下设置每个mapper的行数以及设置InputFormat的代码 
  17.          */  
  18.         configuration.setInt("mapreduce.input.lineinputformat.linespermap"10);  
  19.         Job job = new Job(configuration, "partitioner-job");  
  20.         job.setInputFormatClass(NLineInputFormat.class);    
  21.         job.setJarByClass(JobMain.class);  
  22.         job.setMapperClass(MyMapper.class);  
  23.         job.setMapOutputKeyClass(LongWritable.class);  
  24.         job.setMapOutputValueClass(IntWritable.class);  
  25.         job.setPartitionerClass(MyPartitioner.class);  
  26.         job.setReducerClass(MyReducer.class);  
  27.         job.setOutputKeyClass(Text.class);  
  28.         job.setOutputValueClass(IntWritable.class);  
  29.         job.setNumReduceTasks(2);  
  30.         FileInputFormat.addInputPath(job, new Path(args[0]));  
  31.         Path outputDir = new Path(args[1]);  
  32.         FileSystem fs = FileSystem.get(configuration);  
  33.         if( fs.exists(outputDir)) {  
  34.             fs.delete(outputDir ,true);  
  35.         }  
  36.         FileOutputFormat.setOutputPath(job, outputDir);  
  37.         System.exit(job.waitForCompletion(true) ? 01);  
  38.     }  
  39. }  
运行过程:


从红色框中可以看出测试数据被分成两个split用两个不同的map进行计算。

运行结果:


总结:
这里指定的是每个inputSplit为10行,具体应用时应该根据行的大小以及hdfs的block的大小来设置行数,以使各个map进程能够跑在不同的机器上以提高集群资源的利用率。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值