(2)写出
6.Driver
1 2 3 4 cof.set(KeyValueLineRecordReader.KEY_VALUE_SEPERATOR," " ); job.setInputFormatClass(KeyValueTextInputFormat.class);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package com.atguigu.mr.kv;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Mapper;import java.io.IOException;public class KVTextMapper extends Mapper <Text, Text, Text, IntWritable> { IntWritable intWritable = new IntWritable (1 ); @Override protected void map (Text key, Text value, Context context) throws IOException, InterruptedException { context.write(key, intWritable); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package com.atguigu.mr.kv;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Reducer;import java.io.IOException;public class KVTextReducer extends Reducer <Text, IntWritable, Text, IntWritable> { IntWritable v = new IntWritable (); @Override protected void reduce (Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0 ; for (IntWritable value : values) { sum += value.get(); } v.set(sum); context.write(key, v); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 package com.atguigu.mr.kv;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.input.KeyValueLineRecordReader;import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import java.io.IOException;public class KVTextDriver { public static void main (String[] args) throws IOException, ClassNotFoundException, InterruptedException { args = new String []{"F:/mr0529/input" , "F:/mr0529/output" }; Configuration cof = new Configuration (); cof.set(KeyValueLineRecordReader.KEY_VALUE_SEPERATOR, " " ); Job job = Job.getInstance(cof); job.setJarByClass(KVTextDriver.class); job.setMapperClass(KVTextMapper.class); job.setReducerClass(KVTextReducer.class); job.setMapOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setInputFormatClass(KeyValueTextInputFormat.class); FileInputFormat.setInputPaths(job, new Path (args[0 ])); FileOutputFormat.setOutputPath(job, new Path (args[1 ])); boolean result = job.waitForCompletion(true ); System.exit(result ? 0 : 1 ); } }
如果使用NLineInputFormat
,代表每个map进程处理的InputSplit不再按Block块去划分,而是按NLineInputFormat
指定的行数N来划分。即输入文件的总行数/N=切片数
,如果不整除,切片数=商+1
。
以下是一个示例,仍然以上边的4行输入为例子。
1 2 3 4 Rich learning form Intelligent learning engine Learning more convenient From the real demand for more close to the enterprise
例如,如果N是2,则每个输入分片包含两行。开启3个MapTask。
1 2 (0,Rich learning form) (19,Intelligent learning engine)
另一个mapper则受到后两行:
1 2 (47,Learning more convenient) (72,From the real demand for more close to the enterprise)
这里的键值与TextInputFormat生成的一样,key是偏移量。
需求 对每个单词进行个数统计,要求根据每个输入文件的行数来规定输出多少个切片。此案例要求每三行放入一个切片中。
(1)输入数据
1 2 3 4 5 6 7 8 9 10 11 banzhang ni hao xihuan hadoop banzhang banzhang ni hao xihuan hadoop banzhang banzhang ni hao xihuan hadoop banzhang banzhang ni hao xihuan hadoop banzhang banzhang ni hao xihuan hadoop banzhang banzhang ni hao xihuan hadoop banzhang
(2)期望输出数据
需求分析 1.需求:对每个单词进行个数统计,要求每三行放入一个切片中。 2.输入数据 3.输出数据 4.Map阶段
(1)获取一行 (2)切割 (3)循环写出
5.Reduce阶段
(1)汇总 (2)输出
6.Driver
1 2 NLineInputFormat.setNumLinesPerSplit(job,3 );
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 package com.atguigu.mr.nline;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Mapper;import java.io.IOException;public class NLineMapper extends Mapper <LongWritable, Text, Text, IntWritable> { Text k = new Text (); IntWritable v = new IntWritable (1 ); @Override protected void map (LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] words = line.split(" " ); for (String word : words) { k.set(word); context.write(k, v); } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 package com.atguigu.mr.nline;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Reducer;import java.io.IOException;public class NLineReducer extends Reducer <Text, IntWritable, Text, IntWritable> { IntWritable v = new IntWritable (); @Override protected void reduce (Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0 ; for (IntWritable value : values) { sum += value.get(); } v.set(sum); context.write(key, v); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 package com.atguigu.mr.nline;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.input.NLineInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import java.io.IOException;public class NLineDriver { public static void main (String[] args) throws IOException, ClassNotFoundException, InterruptedException { args = new String []{"F:/mr0529/input" , "F:/mr0529/output" }; Configuration cof = new Configuration (); Job job = Job.getInstance(cof); NLineInputFormat.setNumLinesPerSplit(job, 3 ); job.setInputFormatClass(NLineInputFormat.class); job.setJarByClass(NLineDriver.class); job.setMapperClass(NLineMapper.class); job.setReducerClass(NLineReducer.class); job.setMapOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.setInputPaths(job, new Path (args[0 ])); FileOutputFormat.setOutputPath(job, new Path (args[1 ])); job.waitForCompletion(true ); } }
在企业开发中,Hadoop框架自带的InputFormat类型不能满足所有应用场景,需要自定义InputFormat
来解决实际问题。
自定义InputFormat
步骤如下:
(1)自定义一个类继承FileInputFormat
。 (2)改写RecordReader
,实现一次读取一个完整文件封装为KV
。 (3)在输出时使用SequenceFileOutPutFormat
输出合并文件。
无论HDFS还是MapReduce,在处理小文件时效率都非常低,但又难免面临处理大量小文件的场景,此时,就需要有相应解决方案。可以自定义InputFormat实现小文件的合并。
需求 将多个小文件合并成一个SequenceFile文件(SequenceFile文件是Hadoop用来存储二进制形式的key-value对的文件格式),SequenceFile里面存储着多个文件,存储的形式为文件路径+名称为key,文件内容为value。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 --- one.txt --- yongpeng weidong weinan sanfeng luozong xiaoming --- two.txt --- longlong fanfan mazong kailun yuhang yixin longlong fanfan mazong kailun yuhang yixin --- three.txt --- longlong fanfan mazong kailun yuhang yixin longlong fanfan mazong kailun yuhang yixin
1 2 3 4 5 6 SEQorg.apache.hadoop.io.Text"org.apache.hadoop.io.BytesWritable ?奀Wu授X@鼧? W "!file:/e:/inputinputformat/one.txt 1yongpeng weidong weinan sanfeng luozong xiaoming Y $#file:/e:/inputinputformat/three.txt 1shuaige changmo zhenqiang dongli lingu xuanxuan € "!file:/e:/inputinputformat/two.txt Zlonglong fanfan mazong kailun yuhang yixin longlong fanfan mazong kailun yuhang yixin
需求分析 1、自定义一个类继承FileInputFormat
(1)重写`isSplitable()方法,返回false不可切割
(2)重写createRecordReader()
, 创建自定义的RecordReader对象,并初始化
2、改写RecordReader, 实现一次读取一个完整文件封装为KV
(1)采用IO流一次读取一个文件输出到value中,因为设置了不可切片,最终把所有文件都封装到了value中
(2)获取文件路径信息+名称,并设置key
3、设置Driver
1 2 3 4 5 job.setInputFormatClass(WholeFileInputformat.class); job.set0utputFormatClass(SequenceFileOutputFormat.class);
程序实现 (1)自定义InputFormat
WholeFileInputformat.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 package com.atguigu.mr.inputformat;import org.apache.hadoop.io.BytesWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.InputSplit;import org.apache.hadoop.mapreduce.RecordReader;import org.apache.hadoop.mapreduce.TaskAttemptContext;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import java.io.IOException;public class WholeFileInputFormat extends FileInputFormat <Text, BytesWritable> { @Override public RecordReader<Text, BytesWritable> createRecordReader (InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { WholeRecordReader recordReader = new WholeRecordReader (); recordReader.initialize(inputSplit, taskAttemptContext); return recordReader; } }
(2)自定义RecordReader类
WholeRecordReader.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 package com.atguigu.mr.inputformat;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.FSDataInputStream;import org.apache.hadoop.fs.FileSystem;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.BytesWritable;import org.apache.hadoop.io.IOUtils;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.InputSplit;import org.apache.hadoop.mapreduce.RecordReader;import org.apache.hadoop.mapreduce.TaskAttemptContext;import org.apache.hadoop.mapreduce.lib.input.FileSplit;import java.io.IOException;public class WholeRecordReader extends RecordReader <Text, BytesWritable> { FileSplit split; Configuration configuration; Text k = new Text (); BytesWritable v = new BytesWritable (); Boolean isProgress = true ; @Override public void initialize (InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { this .split = (FileSplit) inputSplit; configuration = taskAttemptContext.getConfiguration(); } @Override public boolean nextKeyValue () throws IOException, InterruptedException { if (isProgress) { byte [] buf = new byte [(int ) split.getLength()]; Path path = split.getPath(); FileSystem fs = path.getFileSystem(configuration); FSDataInputStream fis = fs.open(path); IOUtils.readFully(fis, buf, 0 , buf.length); v.set(buf, 0 , buf.length); k.set(path.toString()); IOUtils.closeStream(fis); isProgress = false ; return true ; } return false ; } @Override public Text getCurrentKey () throws IOException, InterruptedException { return k; } @Override public BytesWritable getCurrentValue () throws IOException, InterruptedException { return v; } @Override public float getProgress () throws IOException, InterruptedException { return 0 ; } @Override public void close () throws IOException { } }
(3)编写SequenceFileMapper类处理流程
SequcnceFileMapper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 package com.atguigu.mr.inputformat;import org.apache.hadoop.io.BytesWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Mapper;import java.io.IOException;public class SequcnceFileMapper extends Mapper <Text, BytesWritable, Text, BytesWritable> { @Override protected void map (Text key, BytesWritable value, Context context) throws IOException, InterruptedException { context.write(key, value); } }
(4)编写SequenceFileReducer类处理流程
SequcnceFileReducer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package com.atguigu.mr.inputformat;import org.apache.hadoop.io.BytesWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Reducer;import java.io.IOException;public class SequcnceFileReducer extends Reducer <Text, BytesWritable, Text, BytesWritable> { @Override protected void reduce (Text key, Iterable<BytesWritable> values, Context context) throws IOException, InterruptedException { for (BytesWritable value : values) { context.write(key, value); } } }
(5)编写SequenceFileDriver类处理流程
SequcnceFileDriver.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 package com.atguigu.mr.inputformat;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.BytesWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;import java.io.IOException;public class SequcnceFileDriver { public static void main (String[] args) throws IOException, ClassNotFoundException, InterruptedException { args = new String []{"f:/IDEAWS/dashuju/input" , "f:/IDEAWS/dashuju/output" }; Configuration conf = new Configuration (); Job job = Job.getInstance(conf); job.setJarByClass(SequcnceFileDriver.class); job.setMapperClass(SequcnceFileMapper.class); job.setReducerClass(SequcnceFileReducer.class); job.setInputFormatClass(WholeFileInputFormat.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(BytesWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(BytesWritable.class); FileInputFormat.setInputPaths(job, new Path (args[0 ])); FileOutputFormat.setOutputPath(job, new Path (args[1 ])); boolean result = job.waitForCompletion(true ); System.exit(result ? 0 : 1 ); } }
MapReduce工作流程
流程详解 上面的流程是整个MapReduce最全工作流程,但是Shuffle过程只是从第7步开始到第16步结束,具体Shuffle过程详解,如下: 1)MapTask收集我们的map()方法输出的kv对,放到内存缓冲区中 2)从内存缓冲区不断溢出本地磁盘文件,可能会溢出多个文件 3)多个溢出文件会被合并成大的溢出文件 4)在溢出过程及合并的过程中,都要调用Partitioner进行分区和针对key进行排序 5)ReduceTask根据自己的分区号,去各个MapTask机器上取相应的结果分区数据 6)ReduceTask会取到同一个分区的来自不同MapTask的结果文件,ReduceTask会将这些文件再进行合并(归并排序) 7)合并成大文件后,Shuffle的过程也就结束了,后面进入ReduceTask的逻辑运算过程(从文件中取出一个一个的键值对Group,调用用户自定义的reduce()方法)
注意 Shuffle中的缓冲区大小会影响到MapReduce程序的执行效率,原则上说,缓冲区越大,磁盘io的次数越少,执行速度就越快。 缓冲区的大小可以通过参数调整,参数:io.sort.mb默认100M。
源码解析流程 1 2 3 4 5 6 7 8 9 10 11 12 context.write(k, NullWritable.get()); output.write(key, value); collector.collect(key, value,partitioner.getPartition(key, value, partitions)); HashPartitioner(); collect() close() collect.flush() sortAndSpill() sort() QuickSort mergeParts () ; collector.close();
Shuffle机制 Shuffle机制 Map方法之后,Reduce方法之前的数据处理过程称之为Shuffle。
Shuffle机制在MapTask和ReduceTask有重叠。
Partition分区 1、问题引出
要求将统计结果按照条件输出到不同文件中(分区)。
比如:将统计结果按照手机归属地不同省份输出到不同文件中(分区)
2、默认Partitioner分区
1 2 3 public class HashPartitioner <K, V> extends Partitioner <K, V> {publiC int getPartition (K key, V value,int numReduceTasks) {return (key .hashCode() & Integer.MAX_ VALUE) % numReduceTasks;
默认分区是根据key的hashCode对ReduceTasks个数取模得到的。用户没法控制哪个key存储到哪个分区。
自定义Partitioner步骤
(1)自定义类继承Partitioner, 重写getPartition()方法
1 2 3 4 5 6 7 8 9 public class CustomPartitioner extends Partitioner <Text, FlowBean> [ @Override public int getPartition (Text key, FlowBean value, int numPartitions) { ... ... return partition; }
(2)在Job驱动中,设置自定义Partitioner
1 job.setPartitionerClass(CustomPartitioner.class);
(3)自定义Partition后, 要根据自定义Partitioner的逻辑设置相应数量的ReduceTask
1 job.setNumReduceTasks(5 );
4、分区总结
(1)如果ReduceTask的数量 > getPatition的结果数
,则会多产性几个空的输出文件part-1-000xx
;
(2)如果1 < ReduceTask的数量 < getPation的结果数
,则有一部分分区数据无处安放,会Exception;
(3)如果ReduceTask的数量 = 1
,则不管MapTask端输出多少个分区文件,最终结果都交给这一个ReduceTask,最终也就只会产生一个结果文件pat-r-00000;
(4)分区号必须从零开始,逐一累加。
5、案例分析
例如:假设自定义分区数为5,则
(1)job.setNumReduceTasks(1);
会正常运行,只不过会产生一个输出文件 (2)job.setNumReduceTasks(2);
会报错 (3) job.setNumReduceTask<(6);
大于5,程序会正常运行,会产生空文件
Partition分区案例实操 需求分析 (1)需求
将统计结果按照手机归属地不同省份输出到不同文件中(分区)
(2)输入数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 1 13736230513 192.196.100.1 www.atguigu.com 2481 24681 200 2 13846544121 192.196.100.2 264 0 200 3 13956435636 192.196.100.3 132 1512 200 4 13966251146 192.168.100.1 240 0 404 5 18271575951 192.168.100.2 www.atguigu.com 1527 2106 200 6 84188413 192.168.100.3 www.atguigu.com 4116 1432 200 7 13590439668 192.168.100.4 1116 954 200 8 15910133277 192.168.100.5 www.hao123.com 3156 2936 200 9 13729199489 192.168.100.6 240 0 200 10 13630577991 192.168.100.7 www.shouhu.com 6960 690 200 11 15043685818 192.168.100.8 www.baidu.com 3659 3538 200 12 15959002129 192.168.100.9 www.atguigu.com 1938 180 500 13 13560439638 192.168.100.10 918 4938 200 14 13470253144 192.168.100.11 180 180 200 15 13682846555 192.168.100.12 www.qq.com 1938 2910 200 16 13992314666 192.168.100.13 www.gaga.com 3008 3720 200 17 13509468723 192.168.100.14 www.qinghua.com 7335 110349 404 18 18390173782 192.168.100.15 www.sogou.com 9531 2412 200 19 13975057813 192.168.100.16 www.baidu.com 11058 48243 200 20 13768778790 192.168.100.17 120 120 200 21 13568436656 192.168.100.18 www.alibaba.com 2481 24681 200 22 13568436656 192.168.100.19 1116 954 200
(3)期望输出数据
手机号136、137、138、139开头都分别放到一个独立的4个文件中,其他开头的放到一个文件中。
(4)增加一个ProvicePartitioner分区
1 2 3 4 5 136 分区0 137 分区1 138 分区2 139 分区3 其他 分区4
(5)Driver驱动类
1 2 3 4 5 job.setPartitionerClass(ProvincePartitioner.class); job.setNumReduceTasks(5 );
3.在案例2.4的基础上,增加一个分区类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package com.atguigu.mapreduce.flowsum;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Partitioner;public class ProvincePartitioner extends Partitioner <Text, FlowBean> { @Override public int getPartition (Text key, FlowBean value, int numPartitions) { String preNum = key.toString().substring(0 , 3 ); int partition = 4 ; if ("136" .equals(preNum)) { partition = 0 ; }else if ("137" .equals(preNum)) { partition = 1 ; }else if ("138" .equals(preNum)) { partition = 2 ; }else if ("139" .equals(preNum)) { partition = 3 ; } return partition; } }
4.在驱动函数中增加自定义数据分区设置和ReduceTask设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 package com.atguigu.mapreduce.flowsum;import java.io.IOException;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;public class FlowsumDriver { public static void main (String[] args) throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException { args = new String []{"e:/output1" ,"e:/output2" }; Configuration configuration = new Configuration (); Job job = Job.getInstance(configuration); job.setJarByClass(FlowsumDriver.class); job.setMapperClass(FlowCountMapper.class); job.setReducerClass(FlowCountReducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(FlowBean.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(FlowBean.class); job.setPartitionerClass(ProvincePartitioner.class); job.setNumReduceTasks(5 ); FileInputFormat.setInputPaths(job, new Path (args[0 ])); FileOutputFormat.setOutputPath(job, new Path (args[1 ])); boolean result = job.waitForCompletion(true ); System.exit(result ? 0 : 1 ); } }
WritableComparable排序 排序概述 排序是MapReduce框架中最重要的操作之一。
MapTask和ReduceTask均会对数据按照key进行排序。该操作属于Hadoop的默认行为。任何应用程序中的数据均会被排序,而不管逻辑上是否需要。
默认排序是按照字典顺序排序,且实现该排序的方法是快速排序。
对于MapTask,它会将处理的结果暂时放到环形缓冲区中,当环形缓冲区使用率达到一定阈值后,再对缓冲区中的数据进行一次快速排序,并将这些有序数据溢写到磁盘上,而当数据处理完毕后,它会对磁盘上所有文件进行归并排序。
对于ReduceTask,它从每个MapTask上远程拷贝相应的数据文件,如果文件大小超过一定阈值,则溢写磁盘上,否则存储在内存中。如果磁盘上文件数目达到一定阈值,则进行一次归并排序以生成一个更大文件;如果内存中文件大小或者数目超过一定阈值,则进行一次合并后将数据溢写到磁盘上。当所有数据拷贝完毕后,ReduceTask统一对内存和磁盘上的所有数据进行一次归并排序。
排序分类 (1)部分排序
MapReduce根据输入记录的键对数据集排序。保证输出的每个文件内部有序。
(2)全排序
最终输出结果只有一个文件,文件内部有序。实现方式是只设置一个ReduceTask。但该方法在处理大型文件时效率极低,因为-台机器处理所有文件,完全丧失了MapReduce所提供的并行架构。
(3)辅助排序: (GroupingComparator分组)
在Reduce端对key进行分组。应用于:在接收的key为bean对象时,想让一个或几个字段相同(全部字段比较不相同)的key进入到同一个reduce方法时,可以采用分组排序。
(4)二次排序
在自定义排序过程中,如果compareTo中的判断条件为两个即为二次排序。
自定义排序WritableComparable (1)原理分析
bean对象做为key传输,需要实现WritableComparable接口重写compareTo方法,就可以实现排序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Override public int compareTo (FlowBean o) { int result; if (sumFlow > bean.getSumFlow()) { result = -1 ; }else if (sumFlow < bean.getSumFlow()) { result = 1 ; }else { result = 0 ; } return result; }
WritableComparable排序案例实操(全排序) 需求分析 (1)需求
根据案例2.3产生的结果再次对总流量进行排序。
(2)输入数据
原始数据 第一次处理后的数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 1 13736230513 192.196.100.1 www.atguigu.com 2481 24681 200 2 13846544121 192.196.100.2 264 0 200 3 13956435636 192.196.100.3 132 1512 200 4 13966251146 192.168.100.1 240 0 404 5 18271575951 192.168.100.2 www.atguigu.com 1527 2106 200 6 84188413 192.168.100.3 www.atguigu.com 4116 1432 200 7 13590439668 192.168.100.4 1116 954 200 8 15910133277 192.168.100.5 www.hao123.com 3156 2936 200 9 13729199489 192.168.100.6 240 0 200 10 13630577991 192.168.100.7 www.shouhu.com 6960 690 200 11 15043685818 192.168.100.8 www.baidu.com 3659 3538 200 12 15959002129 192.168.100.9 www.atguigu.com 1938 180 500 13 13560439638 192.168.100.10 918 4938 200 14 13470253144 192.168.100.11 180 180 200 15 13682846555 192.168.100.12 www.qq.com 1938 2910 200 16 13992314666 192.168.100.13 www.gaga.com 3008 3720 200 17 13509468723 192.168.100.14 www.qinghua.com 7335 110349 404 18 18390173782 192.168.100.15 www.sogou.com 9531 2412 200 19 13975057813 192.168.100.16 www.baidu.com 11058 48243 200 20 13768778790 192.168.100.17 120 120 200 21 13568436656 192.168.100.18 www.alibaba.com 2481 24681 200 22 13568436656 192.168.100.19 1116 954 200
(3)期望输出数据
1 2 3 4 13509468723 7335 110349 117684 13736230513 2481 24681 27162 13956435636 132 1512 1644 13846544121 264 0 264
(4)FlowBean实现WritableComparable接口重写CompareTo方法
1 2 3 4 5 @Override public int compareTo (FlowBean o) { return this .sumFlow > o.getSumFolw() ? -1 : 1 ; }
(5)Mapper类
1 context.write(bean, 手机号)
(6)Reducer类
1 2 3 4 for (Text text : values) { context.write(text, key); }
代码实现 (1)FlowBean对象在在需求1基础上增加了比较功能
FlowBean.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 package com.atguigu.mr.sort;import org.apache.hadoop.io.WritableComparable;import java.io.DataInput;import java.io.DataOutput;import java.io.IOException;public class FlowBean implements WritableComparable <FlowBean> { private long upFlow; private long downFlow; private long sumFlow; public FlowBean () { super (); } public FlowBean (long upFlow, long downFlow) { super (); this .upFlow = upFlow; this .downFlow = downFlow; sumFlow = upFlow + downFlow; } @Override public void write (DataOutput dataOutput) throws IOException { dataOutput.writeLong(upFlow); dataOutput.writeLong(downFlow); dataOutput.writeLong(sumFlow); } @Override public void readFields (DataInput dataInput) throws IOException { upFlow = dataInput.readLong(); downFlow = dataInput.readLong(); sumFlow = dataInput.readLong(); } @Override public int compareTo (FlowBean bean) { int result; if (sumFlow > bean.getSumFlow()){ result = -1 ; } else if (sumFlow < bean.getSumFlow()) { result = 1 ; } else { result = 0 ; } return result; } @Override public String toString () { return upFlow + "\t" + downFlow + "\t" + sumFlow; } public long getUpFlow () { return upFlow; } public long getDownFlow () { return downFlow; } public long getSumFlow () { return sumFlow; } public void setUpFlow (long upFlow) { this .upFlow = upFlow; } public void setDownFlow (long downFlow) { this .downFlow = downFlow; } public void setSumFlow (long sumFlow) { this .sumFlow = sumFlow; } }
(2)编写Mapper类
FlowCountSortMapper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 package com.atguigu.mr.sort;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Mapper;import java.io.IOException;public class FlowCountSortMapper extends Mapper <LongWritable, Text, FlowBean, Text> { FlowBean k = new FlowBean (); Text v = new Text (); @Override protected void map (LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] fields = line.split("\t" ); String phonenum = fields[0 ]; long upFlow = Long.parseLong(fields[1 ]); long downFlow = Long.parseLong(fields[2 ]); long sumFlow = Long.parseLong(fields[3 ]); k.setDownFlow(downFlow); k.setUpFlow(upFlow); k.setSumFlow(sumFlow); v.set(phonenum); context.write(k, v); } }
(3)编写Reducer类
FlowCountSortReducer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 package com.atguigu.mr.sort;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Reducer;import java.io.IOException;public class FlowCountSortReducer extends Reducer <FlowBean, Text, Text, FlowBean> { @Override protected void reduce (FlowBean key, Iterable<Text> values, Context context) throws IOException, InterruptedException { for (Text value : values) { context.write(value, key); } } }
(4)编写Driver类
FlowCountSortDriver.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 package com.atguigu.mr.sort;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import java.io.IOException;public class FlowCountSortDriver { public static void main (String[] args) throws IOException, ClassNotFoundException, InterruptedException { args = new String []{"F:/IDEAWS/dashju/input1" , "F:/IDEAWS/dashju/output2" }; Configuration conf = new Configuration (); Job job = Job.getInstance(conf); job.setJarByClass(FlowCountSortDriver.class); job.setMapperClass(FlowCountSortMapper.class); job.setReducerClass(FlowCountSortReducer.class); job.setMapOutputKeyClass(FlowBean.class); job.setMapOutputValueClass(Text.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(FlowBean.class); FileInputFormat.setInputPaths(job, new Path (args[0 ])); FileOutputFormat.setOutputPath(job, new Path (args[1 ])); boolean result = job.waitForCompletion(true ); System.out.println(result ? 0 : 1 ); } }
WritableComparable排序案例实操(区内排序) 需求分析 要求每个省份手机号输出的文件中按照总流量内部排序。
基于前一个需求,增加自定义分区类,分区按照省份手机号设置。
案例实操 (1)增加自定义分区类
(2)在驱动类中添加分区类
ProvincePartitioner.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package com.atguigu.mr.sort2;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Partitioner;public class ProvincePartitioner extends Partitioner <FlowBean, Text> { @Override public int getPartition (FlowBean flowBean, Text value, int numPartitions) { String prePhoneNum = value.toString().substring(0 , 3 ); int Partition = 4 ; if ("136" .equals(prePhoneNum)) { Partition = 0 ; } else if ("137" .equals(prePhoneNum)) { Partition = 1 ; } else if ("138" .equals(prePhoneNum)) { Partition = 2 ; } else if ("139" .equals(prePhoneNum)) { Partition = 3 ; } return Partition; } }
FlowCountSortDriver.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 package com.atguigu.mr.sort2;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import java.io.IOException;public class FlowCountSortDriver { public static void main (String[] args) throws IOException, ClassNotFoundException, InterruptedException { args = new String []{"F:/IDEAWS/dashju/input3" , "F:/IDEAWS/dashju/output3" }; Configuration conf = new Configuration (); Job job = Job.getInstance(conf); job.setJarByClass(FlowCountSortDriver.class); job.setMapperClass(FlowCountSortMapper.class); job.setReducerClass(FlowCountSortReducer.class); job.setMapOutputKeyClass(FlowBean.class); job.setMapOutputValueClass(Text.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(FlowBean.class); FileInputFormat.setInputPaths(job, new Path (args[0 ])); FileOutputFormat.setOutputPath(job, new Path (args[1 ])); job.setPartitionerClass(ProvincePartitioner.class); job.setNumReduceTasks(5 ); boolean result = job.waitForCompletion(true ); System.out.println(result ? 0 : 1 ); } }
Combiner合并 需求 统计过程中对每一个MapTask的输出进行局部汇总,以减小网络传输量即采用Combiner功能。
(1)Combiner是MR程序中Mapper和Reducer之外的一种组件。 (2)Combiner组件的父类就是Reducer。 (3)Combinen和Reducer的区别在于运行的位置,Combiner是在每一个MapTask所在的节点运行,Reducer是接收全局所有Mapper的输出结果; (4)Combiner的意义就是对每一个MapTask的输出进行局部汇总,以减小网络传输量。 (5)Combiner能够应用的前提是不能影响最终的业务逻辑,而且,Combiner的输出kv应该跟Reducer的输入kv类型要对应起来。
在Mapper阶段:
1 2 3 5 7 -》 (3+5+7)/3=5 2 6 -》(2+6)/2=4
在Reduce阶段:
1 (3+5+7+2+6)/5=23/5 不等于 (5+4)/2=9/2
这种情况下使用combiner就会影响真实的业务逻辑
(6)自定义Combiner实现步骤
(a)自定义一个Combiner继承Reducer,重写Reduce方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class WordcountCombiner extends Reducer <Text, IntWritable, Text,IntWritable>{ @Override protected void reduce (Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException { int count = 0 ; for (IntWritable v :values){ count += v.get(); } context.write(key, new IntWritable (count)); } }
(b)在Job驱动类中设置:
1 job.setCombinerClass(WordcountCombiner.class);
Combiner合并案例实操 需求分析 (1)需求
统计过程中对每一个MapTask的输出进行局部汇总,以减小网络传输量即采用Combiner功能。
(2)数据输入
1 2 3 4 5 6 banzhang ni hao xihuan hadoop banzhang banzhang ni hao xihuan hadoop banzhang
1 2 3 4 5 <banzhang,4> <ni,2> <hao,2> <xihuan,2> <hadoop,2>
(3)期望输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Map-Reduce Framework Map input records=6 Map output records=12 Map output bytes=126 Map output materialized bytes=66 Input split bytes=121 Combine input records=12 Combine output records=5 Reduce input groups=5 Reduce shuffle bytes=66 Reduce input records=5 Reduce output records=5 Spilled Records=10 Shuffled Maps =1 Failed Shuffles=0 Merged Map outputs=1 GC time elapsed (ms)=9 Total committed heap usage (bytes)=2058354688
正常wordcount控制台输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Map-Reduce Framework Map input records=6 Map output records=12 Map output bytes=126 Map output materialized bytes=156 Input split bytes=121 Combine input records=0 Combine output records=0 Reduce input groups=5 Reduce shuffle bytes=156 Reduce input records=12 Reduce output records=5 Spilled Records=24 Shuffled Maps =1 Failed Shuffles=0 Merged Map outputs=1 GC time elapsed (ms)=14 Total committed heap usage (bytes)=2058354688
(4)方案一
增加一个WordcountCombiner类继承Reducer 在WordcountCombiner中,统计单词汇总,将统计结果输出
(5)方案二
将WordcountReducer作为Combiner在WordcountDriver驱动类中指定job.setCombinerClass(WordcountCombiner.class);
案例实操-方案一
增加一个WordcountCombiner类继承Reducer
WordcountCombiner.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 package com.atguigu.mr.combiner1;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Reducer;import java.io.IOException;public class WordcountCombiner extends Reducer <Text, IntWritable, Text, IntWritable> { IntWritable v = new IntWritable (); @Override protected void reduce (Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0 ; for (IntWritable value : values) { sum += value.get(); } v.set(sum); context.write(key, v); } }
在WordcountDriver驱动类中指定Combiner
1 2 job.setCombinerClass(WordcountCombiner.class);
案例实操-方案二
将WordcountReducer作为Combiner在WordcountDriver驱动类中指定
1 2 job.setCombinerClass(WordcountReducer.class);
GroupingComparator分组(辅助排序) 对Reduce阶段的数据根据某一个或几个字段进行分组。
分组排序步骤 : (1)自定义类继承WritableComparator (2)重写compare()方法
1 2 3 4 5 @Override public int compare (WritableComparable a, WritableComparable b) { return result; }
(3)创建一个构造将比较对象的类传给父类
1 2 3 protected OrderGroupingComparator () { super (OrderBean.class, true ); }
GroupingComparator分组案例实操 需求分析 (1)需求
有如下订单数据
订单id
商品id
成交金额
0000001
Pdt_01
222.8
Pdt_02
33.8
0000002
Pdt_03
522.8
Pdt_04
122.4
Pdt_05
722.4
0000003
Pdt_06
232.8
Pdt_02
33.8
现在需要求出每一个订单中最贵的商品
(2)输入数据
1 2 3 4 5 6 7 0000001 Pdt_01 222.8 0000002 Pdt_05 722.4 0000001 Pdt_02 33.8 0000003 Pdt_06 232.8 0000003 Pdt_02 33.8 0000002 Pdt_03 522.8 0000002 Pdt_04 122.4
(3)期望输出
(4)思路分析
a.利用订单id和成交金额
作为key,可以将Map阶段读取到的所有订单数据按照id升序排序,如果id相同再按照金额降序排序,发送到Reduce。 b.在Reduce端利用groupingComparator将订单id相同的kv聚合成组,然后取第一个即是该订单中最贵商品,
(5)MapTask阶段
a.Map中处理的事情:
获取一行 切割出每个字段 一行封装成bean对象
1 2 3 4 5 6 7 8 订单id 价格 bean1,nullwritable 0000001 222.8 bean2,nullwritable 0000002 722.4 bean3,nullwritable 0000001 33.8 bean4,nullwritable 0000003 232.8 bean5,nullwritable 0000003 33.8 bean6,nullwritable 0000002 522.8 bean7,nullwritable 0000002 122.4
b.二次排序
先根据订单id排序,如果订单id相同再根据价格降序排序
1 2 3 4 5 6 7 0000001 222.8 0000001 33.8 0000002 722.4 0000002 522.8 0000002 122.4 0000003 232.8 0000004 33.8
(6)ReduceTask阶段
a.辅助排序
对从map端拉去过来的数据再次进行排序,只要订单id相同就认为是相同key。
b.Reduce方法只把第一组key的第一个写出去
代码实现 (1)定义订单信息OrderBean类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 package com.atguigu.mr.order;import org.apache.hadoop.io.WritableComparable;import java.io.DataInput;import java.io.DataOutput;import java.io.IOException;public class OrderBean implements WritableComparable <OrderBean> { private int order_id; private double order_price; public int getOrder_id () { return order_id; } public double getOrder_price () { return order_price; } public void setOrder_id (int order_id) { this .order_id = order_id; } public void setOrder_price (double order_price) { this .order_price = order_price; } public OrderBean () { super (); } public OrderBean (int oredr_id, double price) { this .order_id = oredr_id; this .order_price = price; } @Override public void write (DataOutput out) throws IOException { out.writeInt(order_id); out.writeDouble(order_price); } @Override public void readFields (DataInput in) throws IOException { order_id = in.readInt(); order_price = in.readDouble(); } @Override public int compareTo (OrderBean o) { int result = 0 ; if (order_id > o.getOrder_id()) { result = 1 ; } else if (order_id < o.getOrder_id()) { result = -1 ; } else { if (order_price > o.getOrder_price()) { result = 1 ; } else if (order_price < o.getOrder_price()) { result = -1 ; } else { result = 0 ; } } return result; } @Override public String toString () { return order_id + "\t" + order_price; } }
(2)编写OrderSortMapper类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 package com.atguigu.mr.order;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Mapper;import java.io.IOException;public class OrderSortMapper extends Mapper <LongWritable, Text, OrderBean, NullWritable> { OrderBean k = new OrderBean (); @Override protected void map (LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] fields = line.split(" " ); k.setOrder_id(Integer.parseInt(fields[0 ])); k.setOrder_price(Double.parseDouble(fields[2 ])); context.write(k, NullWritable.get()); } }
(3)编写OrderSortReducer类
1 2 3 4 5 6 7 8 9 10 11 12 13 package com.atguigu.mr.order;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.mapreduce.Reducer;import java.io.IOException;public class OrderReducer extends Reducer <OrderBean, NullWritable, OrderBean, NullWritable> { @Override protected void reduce (OrderBean key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException { context.write(key, NullWritable.get()); } }
(4)编写OrderSortDriver类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 package com.atguigu.mr.order;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import java.io.IOException;public class OrderDriver { public static void main (String[] args) throws IOException, ClassNotFoundException, InterruptedException { args = new String []{"F:/IDEAWS/dashju/orderinput1" , "F:/IDEAWS/dashju/orderoutput1" }; Configuration conf = new Configuration (); Job job = Job.getInstance(conf); job.setJarByClass(OrderDriver.class); job.setMapperClass(OrderSortMapper.class); job.setReducerClass(OrderSortReducer.class); job.setMapOutputKeyClass(OrderBean.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputKeyClass(OrderBean.class); job.setOutputValueClass(NullWritable.class); FileInputFormat.setInputPaths(job, new Path (args[0 ])); FileOutputFormat.setOutputPath(job, new Path (args[1 ])); boolean result = job.waitForCompletion(true ); System.exit(result ? 0 : 1 ); } }
在不分组前运行得到结果为
1 2 3 4 5 6 7 1 222.8 1 33.8 2 722.4 2 522.8 2 122.4 3 232.8 3 33.8
结果表明key不相同,key.id相同,所以输出按照不同对象输出。
(5)编写OrderSortGroupingComparator类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 package com.atguigu.mr.order;import org.apache.hadoop.io.WritableComparable;import org.apache.hadoop.io.WritableComparator;public class OrderGroupingComparator extends WritableComparator { protected OrderGroupingComparator () { super (OrderBean.class, true ); } @Override public int compare (WritableComparable a, WritableComparable b) { int result; OrderBean orderBean_a = (OrderBean) a; OrderBean orderBean_b = (OrderBean) b; if (orderBean_a.getOrder_id() > orderBean_b.getOrder_id()) { result = 1 ; } else if (orderBean_a.getOrder_id() < orderBean_b.getOrder_id()) { result = -1 ; } else { result = 0 ; } return result; } }
(6)增加Driver驱动关联
1 2 job.setGroupingComparatorClass(OrderGroupingComparator.class);
运行结果:
想要输出top3,在reducer中循环输出即可
1 2 3 for (NullWritable nullWritable : values) { context.write(key, NullWritable.get()); }
MapTask工作机制 MapTask + ReduceTask = MapReduce
-(1)Read阶段:MapTask通过用户编写的RecordReader
,从输入InputSplit
中解析出一个个key/value
。
-(2)Map阶段:该节点主要是将解析出的key/value
交给用户编写map()
函数处理,并产生一系列新的key/value
。
-(3)Collect收集阶段:在用户编写map()
函数中,当数据处理完成后,一般会调用OutputCollector.collect()
输出结果。在该函数内部,它会将生成的key/value
分区(调用Partitioner
),并写入一个环形内存缓冲区中。
-(4)Spill阶段:即溢写
,当环形缓冲区满后,MapReduce会将数据写到本地磁盘上,生成一个临时文件。需要注意的是,将数据写入本地磁盘之前,先要对数据进行一次本地排序,并在必要时对数据进行合并、压缩等操作。
步骤1:利用快速排序算法对缓存区内的数据进行排序,排序方式是,先按照分区编号Partition进行排序,然后按照key进行排序。这样,经过排序后,数据以分区为单位聚集在一起,且同一分区内所有数据按照key有序。
步骤2:按照分区编号由小到大依次将每个分区中的数据写入任务工作目录下的临时文件output/spillN.out
(N表示当前溢写次数)中。如果用户设置了Combiner,则写入文件之前,对每个分区中的数据进行一次聚集操作。
步骤3:将分区数据的元信息写到内存索引数据结构SpillRecord中,其中每个分区的元信息包括在临时文件中的偏移量、压缩前数据大小和压缩后数据大小。如果当前内存索引大小超过1MB,则将内存索引写到文件output/spillN.out.index
中。
-(5)Combine阶段:当所有数据处理完成后,MapTask对所有临时文件进行一次合并,以确保最终只会生成一个数据文件。
当所有数据处理完后,MapTask会将所有临时文件合并成一个大文件,并保存到文件output/file.out
中,同时生成相应的索引文件output/file.out.index
。
在进行文件合并过程中,MapTask以分区为单位进行合并。对于某个分区,它将采用多轮递归合并的方式。每轮合并io.sort.factor
(默认10)个文件,并将产生的文件重新加入待合并列表中,对文件排序后,重复以上过程,直到最终得到一个大文件。
让每个MapTask最终只生成一个数据文件,可避免同时打开大量文件和同时读取大量小文件产生的随机读取带来的开销。
ReduceTask工作机制 ReduceTask工作机制
(1)Copy阶段:ReduceTask从各个MapTask上远程拷贝一片数据,并针对某一片数据,如果其大小超过一定阈值,则写到磁盘上,否则直接放到内存中。
(2)Merge阶段:在远程拷贝数据的同时,ReduceTask启动了两个后台线程对内存和磁盘上的文件进行合并,以防止内存使用过多或磁盘上文件过多。
(3)Sort阶段:按照MapReduce语义,用户编写reduce()
函数输入数据是按key进行聚集的一组数据。为了将key相同的数据聚在一起,Hadoop采用了基于排序的策略。由于各个MapTask已经实现对自己的处理结果进行了局部排序,因此,ReduceTask只需对所有数据进行一次归并排序
即可。
(4)Reduce阶段:reduce()
函数将计算结果写到HDFS上。
设置ReduceTask并行度(个数) ReduceTask的并行度同样影响整个Job的执行并发度和执行效率,但与MapTask的并发数由切片数决定不同,ReduceTask数量的决定是可以直接手动设置:
1 2 job.setNumReduceTasks(4 );
实验:测试ReduceTask多少合适 (1)实验环境:1个Master节点,16个Slave节点:CPU:8GHZ,内存: 2G,数据量为1G。 (2)实验结论:
MapTask =16
ReduceTask
1
5
10
15
16
20
25
30
45
60
总时间
892
146
110
92
88
100
128
101
145
104
实验结果符合正态分布,个数和集群环境因素有关。
注意事项 -(1)ReduceTask=0
, 表示没有Reduce阶段,输出文件个数和Map个数一致。
-(2)ReduceTask默认值就是1, 所以输出文件个数为一个。
-(3)如果数据分布不均匀,就有可能在Reduce阶段产生数据倾斜。
-(4)ReduceTask数量并不是任意设置,还要考虑业务逻辑需求,有些情况下,需要计算全局汇总结果,就只能有1个ReduceTask。
-(5)具体多少个ReduceTask,需要根据集群性能而定。
-(6)如果分区数不是1,但是ReduceTask为1, 是否执行分区过程。答案是:不执行分区过程。因为在MapTask的源码中,执行分区的前提是先判断ReduceNum个数是否大于1。不大于1肯定不执行。
OutputFornat是MapReduce输出的基类,所有实现MapReduce输出都实现了OutputFormat接口。下面我们介 绍几种常见的OutputFormat实现类。
1.文本输出TextOutputFormat
默认的输出格式是’TextOutputFomat,它把每条记录写为文本行
。它的键和值可以是任意类型,因为TextOutputFormat调 用toString(方法把它们转换为字符串。
SequenceFileOutputFormat
将SequenceFileOutputFormat输出作为后续MapReduce任务的输入,这便是一种好的输出格式,因为它的格式紧凑,很容易被压缩。
3.自定义OutputFormat
根据用户需求,自定义实现输出。
自定义OutputFromat 使用场景 为了试验控制最终该文件的输出路径和输出格式,可以自定义OutputFormat。
例如:要在一个MapReduce程序中根据数据的不同输出两类结果到不同目录,这类灵活的输出需求可以通过自定义OutPutForamt来实现。
(1)自定义一个类继承FileOutputFormat。 (2)改写RecordWriter,具体改写输出数据的方法write()
。
需求分析 需求 过滤输入的log日志,包含atguigu的网站输出到f:/IDEAWS/dashuju/atguigu.log
,不包含atguigu的网站输出到f:/IDEAWS/dashuju/other.log
。
输入数据 1 2 3 4 5 6 7 8 9 http://www.baidu.com http://www.google.com http://cn.bing.com http://www.atguigu.com http://www.sohu.com http://www.sina.com http://www.sin2a.com http://www.sin2desa.com http://www.sindsafa.com
期望输出数据 atguigu.log
other.log
1 2 3 4 5 6 7 8 http://cn.bing.com http://www.baidu.com http://www.google.com http://www.sin2a.com http://www.sin2desa.com http://www.sina.com http://www.sindsafa.com http://www.sohu.com
(1)创建一个类FileRecordWriter继承RecordWriter
(a)创建两个文件的输出流:atguiguOut、otherOut; (b)如果输入数据包含atguigu,输出到atguiguOut流;如果不包含atguigu,输出到otherOut流。
驱动类Driver 1 2 job.setOutputFormatClass(FilterOutputFormat.class);
案例实操
FilterMapper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 package com.atguigu.mr.outputformat;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Mapper;import java.io.IOException;public class FilterMapper extends Mapper <LongWritable, Text, Text, NullWritable> { @Override protected void map (LongWritable key, Text value, Context context) throws IOException, InterruptedException { context.write(value, NullWritable.get()); } }
FilterReducer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package com.atguigu.mr.outputformat;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Reducer;import java.io.IOException;public class FilterReducer extends Reducer <Text, NullWritable, Text, NullWritable> { Text k = new Text (); @Override protected void reduce (Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException { String line = key.toString(); line = line + "\r\n" ; k.set(line); for (NullWritable nullWritable : values) { context.write(k, NullWritable.get()); } } }
FilterOutputFormat.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package com.atguigu.mr.outputformat;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.RecordWriter;import org.apache.hadoop.mapreduce.TaskAttemptContext;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import java.io.IOException;public class FilterOutputFormat extends FileOutputFormat <Text, NullWritable> { @Override public RecordWriter<Text, NullWritable> getRecordWriter (TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { return new FRecordWriter (taskAttemptContext); } }
FRecordWriter.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 package com.atguigu.mr.outputformat;import org.apache.hadoop.fs.FSDataOutputStream;import org.apache.hadoop.fs.FileSystem;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.IOUtils;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.RecordWriter;import org.apache.hadoop.mapreduce.TaskAttemptContext;import java.io.IOException;public class FRecordWriter extends RecordWriter <Text, NullWritable> { FSDataOutputStream fosatguigu; FSDataOutputStream fosother; public FRecordWriter (TaskAttemptContext job) { try { FileSystem fs = FileSystem.get(job.getConfiguration()); fosatguigu = fs.create(new Path ("f:/IDEAWS/dashju/atguigu.log" )); fosother = fs.create(new Path ("f:/IDEAWS/dashju/other.log" )); } catch (IOException e) { e.printStackTrace(); } } @Override public void write (Text text, NullWritable nullWritable) throws IOException, InterruptedException { if (text.toString().contains("atguigu" )) { fosatguigu.write(text.toString().getBytes()); } else { fosother.write(text.toString().getBytes()); } } @Override public void close (TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { IOUtils.closeStream(fosatguigu); IOUtils.closeStream(fosother); } }
FilterDrvier.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 package com.atguigu.mr.outputformat;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import java.io.IOException;public class FilterDrvier { public static void main (String[] args) throws IOException, ClassNotFoundException, InterruptedException { args = new String []{"F:/IDEAWS/dashju/inputformat" , "F:/IDEAWS/dashju/outputformat" }; Configuration conf = new Configuration (); Job job = Job.getInstance(conf); job.setJarByClass(FilterDrvier.class); job.setMapperClass(FilterMapper.class); job.setReducerClass(FilterReducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(NullWritable.class); job.setOutputFormatClass(FilterOutputFormat.class); FileInputFormat.setInputPaths(job, new Path (args[0 ])); FileOutputFormat.setOutputPath(job, new Path (args[1 ])); boolean result = job.waitForCompletion(true ); System.exit(result ? 0 : 1 ); } }
Join多种应用 Reduce Join
Map端的主要工作:为来自不同表或文件的key/value对,打标签以区别不同来源的记录
。然后用连接字段作为key,其余部分和新加的标志作为value,最后进行输出。
Reduce端的主要工作:在Reduce端以连接字段作为key的分组已经完成,我们只需要在每一个分组当中将那些来源于不同文件的记录(在Map阶段已经打标志)分开
,最后进行台并就k了。
合并操作在reduce阶段完成,压力大,map端负载率极低,资源利用率不高,极易在reduce阶段产生数据倾斜。
Reduce Join案例实操 需求分析 通过将关联条件作为Map输出的key,将两表满足Join条件的数据并携带数据所来源的文件信息,发往同一个ReduceTask,在Reduce中进行数据的串联,
需求 将商品信息表中数据根据商品pid合并到订单数据表中。
输入数据
order.txt - t_order
id
pid
amount
1001
01
1
1002
02
2
1003
03
3
1004
01
4
1005
02
5
1006
03
6
1 2 3 4 5 6 1001 01 1 1002 02 2 1003 03 3 1004 01 4 1005 02 5 1006 03 6
pd.txt - t_product
pid
pname
01
小米
02
华为
03
格力
输出数据
id
pname
amount
1001
小米
1
1004
小米
4
1002
华为
2
1005
华为
5
1003
格力
3
1006
格力
6
1 2 3 4 5 6 7 id pname amount 1001 小米 1 1004 小米 4 1002 华为 2 1005 华为 5 1003 格力 3 1006 格力 6
MapTask
获取输入文件类型 获取输入数据 不同文件分别处理 封装Bean对象输出
1 2 3 4 5 6 7 8 9 10 11 01 1001 1 order 02 1002 2 order 03 1003 3 order 01 1001 1 order 02 1002 2 order 03 1003 3 order 01 小米 pd 02 华为 pd 03 格力 pd
1 2 3 4 5 6 7 8 9 10 11 01 1001 1 order 01 1001 1 order 01 小米 pd 02 1002 2 order 02 1002 2 order 02 华为 pd 03 1003 3 order 03 1003 3 order 03 格力 pd
ReduceTask 缓存订单数据集合和产品表,然后合并
1 2 3 4 5 6 7 8 9 订单id 产品名称 数量 1001 小米 1 1001 小米 1 1002 华为 2 1002 华为 2 1003 格力 3 1003 格力 3
代码实现
TableBean.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 package com.atguigu.mr.table;import org.apache.hadoop.io.Writable;import java.io.DataInput;import java.io.DataOutput;import java.io.IOException;public class TableBean implements Writable { private String id; private String pid; private int amount; private String pname; private String flag; public TableBean () { super (); } public TableBean (String id, String pid, int amount, String pname, String flag) { this .id = id; this .pid = pid; this .amount = amount; this .pname = pname; this .flag = flag; } public String getId () { return id; } public String getPid () { return pid; } public int getAmount () { return amount; } public String getPname () { return pname; } public String getFlag () { return flag; } public void setId (String id) { this .id = id; } public void setPid (String pid) { this .pid = pid; } public void setAmount (int amount) { this .amount = amount; } public void setPname (String pname) { this .pname = pname; } public void setFlag (String flag) { this .flag = flag; } @Override public String toString () { return id + "\t" + amount + "\t" + pname; } @Override public void write (DataOutput out) throws IOException { out.writeUTF(id); out.writeUTF(pid); out.writeInt(amount); out.writeUTF(pname); out.writeUTF(flag); } @Override public void readFields (DataInput in) throws IOException { id = in.readUTF(); pid = in.readUTF(); amount = in.readInt(); pname = in.readUTF(); flag = in.readUTF(); } }
TableMapper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 package com.atguigu.mr.table;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Mapper;import org.apache.hadoop.mapreduce.lib.input.FileSplit;import java.io.IOException;public class TableMapper extends Mapper <LongWritable, Text, Text, TableBean> { String name; @Override protected void setup (Context context) throws IOException, InterruptedException { FileSplit inputSplit = (FileSplit) context.getInputSplit(); name = inputSplit.getPath().getName(); } TableBean tableBean = new TableBean (); Text k = new Text (); @Override protected void map (LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); if (name.startsWith("order" )) { String[] splits = line.split("\t" ); tableBean.setId(splits[0 ]); tableBean.setPid(splits[1 ]); tableBean.setAmount(Integer.parseInt(splits[2 ])); tableBean.setPname("" ); tableBean.setFlag("order" ); k.set(splits[1 ]); } else { String[] splits = line.split("\t" ); tableBean.setId("" ); tableBean.setPid(splits[0 ]); tableBean.setAmount(0 ); tableBean.setPname(splits[1 ]); tableBean.setFlag("pd" ); k.set(splits[0 ]); } context.write(k, tableBean); } }
TableReducer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 package com.atguigu.mr.table;import org.apache.commons.beanutils.BeanUtils;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Reducer;import java.io.IOException;import java.lang.reflect.InvocationTargetException;import java.util.ArrayList;public class TableReducer extends Reducer <Text, TableBean, TableBean, NullWritable> { @Override protected void reduce (Text key, Iterable<TableBean> values, Context context) throws IOException, InterruptedException { ArrayList<TableBean> orderBeans = new ArrayList <>(); TableBean pdBean = new TableBean (); for (TableBean bean : values) { if ("order" .equals(bean.getFlag())) { TableBean tempBean = new TableBean (); try { BeanUtils.copyProperties(tempBean, bean); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } orderBeans.add(tempBean); } else { try { BeanUtils.copyProperties(pdBean, bean); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } for (TableBean bean : orderBeans) { bean.setPname(pdBean.getPname()); context.write(bean, NullWritable.get()); } } }
TableDriver.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 package com.atguigu.mr.table;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import java.io.IOException;public class TableDriver { public static void main (String[] args) throws IOException, ClassNotFoundException, InterruptedException { args = new String []{"F:/IDEAWS/dashju/inputtable" , "F:/IDEAWS/dashju/outputtable" }; Configuration configuration = new Configuration (); Job job = Job.getInstance(configuration); job.setJarByClass(TableDriver.class); job.setMapperClass(TableMapper.class); job.setReducerClass(TableReducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(TableBean.class); job.setOutputKeyClass(TableBean.class); job.setOutputValueClass(NullWritable.class); FileInputFormat.setInputPaths(job, new Path (args[0 ])); FileOutputFormat.setOutputPath(job, new Path (args[1 ])); boolean result = job.waitForCompletion(true ); System.exit(result ? 0 : 1 ); } }
Map Join 使用场景 Map Join适用于一张表十分小、一张表很大的场景。
优点 思考:在Reduce端处理过多的表,非常容易产生数据倾斜。怎么办? 在Map端缓存多张表,提前处理业务逻辑,这样增加Map端业务,减少Reduce端数据的压力,尽可能的减少数据倾斜。
具体办法:采用DistributedCache (1)在Mapper的setup阶段,将文件读取到缓存集合中。 (2)在驱动函数中加载缓存。
1 2 job.addCacheFile(new URI ("file://e:/IDEAWS/dashju/inputtable/pd.txt" ));
需求分析 需求 同redece join
1)DistributedCacheDriver 缓存文件
1 2 3 4 job.addCacheFile(new URI ("file://e:/IDEAWS/dashju/inputtable/pd.txt" )); job.setNumReduceTasks(0 );
2)读取缓存的文件数据
代码实现
DistributedCacheDriver.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 package com.atguigu.mr.cache;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import java.io.IOException;import java.net.URI;import java.net.URISyntaxException;public class DistributedCacheDriver { public static void main (String[] args) throws InterruptedException, IOException, ClassNotFoundException, URISyntaxException { args = new String []{"F:/IDEAWS/dashju/inputtable2" , "F:/IDEAWS/dashju/outputtable2" }; Configuration configuration = new Configuration (); Job job = Job.getInstance(configuration); job.setJarByClass(DistributedCacheDriver.class); job.setMapperClass(DistributedCacheMapper.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(NullWritable.class); FileInputFormat.setInputPaths(job, new Path (args[0 ])); FileOutputFormat.setOutputPath(job, new Path (args[1 ])); job.addCacheFile(new URI ("file:///f:/IDEAWS/dashju/inputtable/pd.txt" )); job.setNumReduceTasks(0 ); boolean result = job.waitForCompletion(true ); System.exit(result ? 0 : 1 ); } }
DistributedCacheMapper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 package com.atguigu.mr.cache;import org.apache.commons.lang.StringUtils;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Mapper;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.net.URI;import java.util.HashMap;import java.util.Map;public class DistributedCacheMapper extends Mapper <LongWritable, Text, Text, NullWritable> { Map<String, String> pdMap = new HashMap <>(); @Override protected void setup (Context context) throws IOException, InterruptedException { URI[] cacheFiles = context.getCacheFiles(); String path = cacheFiles[0 ].getPath().toString(); BufferedReader reader = new BufferedReader (new InputStreamReader (new FileInputStream (path), "UTF-8" )); String line; while (StringUtils.isNotEmpty(line = reader.readLine())) { String[] fields = line.split("\t" ); pdMap.put(fields[0 ], fields[1 ]); } reader.close(); } Text k = new Text (); @Override protected void map (LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] fields = line.split("\t" ); String pId = fields[1 ]; String pdName = pdMap.get(pId); k.set(fields[1 ] + "\t" + pdName + "\t" + fields[2 ]); context.write(k, NullWritable.get()); } }
计数器应用 Hadoop为每个作业维护若干内置计数器,以秒数多项指标。例如,某些计数器记录已处理的字节数和记录数,使用户可监控已处理的输入数据量和已产生的输出数据量。
(1)采用枚举的方式统计计数
1 2 3 enum MyCounter {MALFORORMED, NORMAL}context.getCounter(MyCounter.MALFORORMED).increment(1 );
(2)采用计数器组、计数器名称的方式统计
1 2 context.getCounter("counterGroup" , "counter" ).increment(1 );
(3)计数结果在程序运行后的控制台上查看
数据清洗(ETL) 在运行核心业务MapReduce之前,需要对数据进行清洗,清理掉不符合用户要求的数据。清理的过程只需要运行Mapper程序,不需要运行Reduce程序。
需求
1 2 3 web.log(14619 line) 60.208.6.156 - - [18/Sep/2013:06:49:48 +0000] "GET /wp-content/uploads/2013/07/rcassandra.png HTTP/1.0" 200 185524 "http://cos.name/category/software/packages/" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36"
需求分析 需要在Map阶段对输入的数据根据规则进行过滤清洗。
实现代码-简单版
LogMapper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 package com.atguigu.mr.log;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Mapper;import java.io.IOException;public class LogMapper extends Mapper <LongWritable, Text, Text, NullWritable> { @Override protected void map (LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); Boolean result = parseLog(line, context); if (!result) { return ; } context.write(value, NullWritable.get()); } private Boolean parseLog (String line, Context context) { String[] fields = line.split(" " ); if (fields.length > 11 ) { context.getCounter("map" , "true" ).increment(1 ); return true ; } else { context.getCounter("map" , "false" ).increment(1 ); return false ; } } }
LogDriver.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 package com.atguigu.mr.log;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import java.io.IOException;public class LogDriver { public static void main (String[] args) throws InterruptedException, IOException, ClassNotFoundException { args = new String []{"F:/IDEAWS/dashju/inputlog" , "F:/IDEAWS/dashju/outputlog" }; Configuration conf = new Configuration (); Job job = Job.getInstance(conf); job.setJarByClass(LogDriver.class); job.setMapperClass(LogMapper.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(NullWritable.class); job.setNumReduceTasks(0 ); FileInputFormat.setInputPaths(job, new Path (args[0 ])); FileOutputFormat.setOutputPath(job, new Path (args[1 ])); job.waitForCompletion(true ); } }
1 2 3 4 //控制台输出 map false=849 true=13770
结果汇总数据变为13770 line
实现代码-复杂版
(1)定义一个bean,用来记录日志数据中的各数据字段
LogBean.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 package com.atguigu.mr.log2;public class LogBean { private String remote_addr; private String remote_user; private String time_local; private String request; private String status; private String body_bytes_sent; private String http_referer; private String http_user_agent; private boolean valid = true ; public LogBean () { super (); } public LogBean (String remote_addr, String remote_user, String time_local, String request, String status, String body_bytes_sent, String http_referer, String http_user_agent, boolean valid) { this .remote_addr = remote_addr; this .remote_user = remote_user; this .time_local = time_local; this .request = request; this .status = status; this .body_bytes_sent = body_bytes_sent; this .http_referer = http_referer; this .http_user_agent = http_user_agent; this .valid = valid; } public void setRemote_addr (String remote_addr) { this .remote_addr = remote_addr; } public void setRemote_user (String remote_user) { this .remote_user = remote_user; } public void setTime_local (String time_local) { this .time_local = time_local; } public void setRequest (String request) { this .request = request; } public void setStatus (String status) { this .status = status; } public void setBody_bytes_sent (String body_bytes_sent) { this .body_bytes_sent = body_bytes_sent; } public void setHttp_referer (String http_referer) { this .http_referer = http_referer; } public void setHttp_user_agent (String http_user_agent) { this .http_user_agent = http_user_agent; } public void setValid (boolean valid) { this .valid = valid; } public String getRemote_addr () { return remote_addr; } public String getRemote_user () { return remote_user; } public String getTime_local () { return time_local; } public String getRequest () { return request; } public String getStatus () { return status; } public String getBody_bytes_sent () { return body_bytes_sent; } public String getHttp_referer () { return http_referer; } public String getHttp_user_agent () { return http_user_agent; } public boolean isValid () { return valid; } @Override public String toString () { StringBuilder sb = new StringBuilder (); sb.append(this .valid); sb.append("\001" ).append(this .remote_addr); sb.append("\001" ).append(this .remote_user); sb.append("\001" ).append(this .time_local); sb.append("\001" ).append(this .request); sb.append("\001" ).append(this .status); sb.append("\001" ).append(this .body_bytes_sent); sb.append("\001" ).append(this .http_referer); sb.append("\001" ).append(this .http_user_agent); return sb.toString(); } }
LogMapper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 package com.atguigu.mr.log2;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Mapper;import java.io.IOException;public class LogMapper extends Mapper <LongWritable, Text, Text, NullWritable> { Text k = new Text (); @Override protected void map (LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); LogBean logBean = parseLog(line); if (!logBean.isValid()) { return ; } k.set(logBean.toString()); context.write(k, NullWritable.get()); } private LogBean parseLog (String line) { LogBean logBean = new LogBean (); String[] fields = line.split(" " ); if (fields.length > 11 ) { logBean.setRemote_addr(fields[0 ]); logBean.setRemote_user(fields[1 ]); logBean.setTime_local(fields[3 ].substring(1 )); logBean.setRequest(fields[6 ]); logBean.setStatus(fields[8 ]); logBean.setBody_bytes_sent(fields[9 ]); logBean.setHttp_referer(fields[10 ]); if (fields.length > 12 ) { logBean.setHttp_user_agent(fields[11 ] + " " + fields[12 ]); } else { logBean.setHttp_user_agent(fields[11 ]); } if (Integer.parseInt(logBean.getStatus()) >= 400 ) { logBean.setValid(false ); } } else { logBean.setValid(false ); } return logBean; } }
LogDriver.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 package com.atguigu.mr.log2;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import java.io.IOException;public class LogDriver { public static void main (String[] args) throws InterruptedException, IOException, ClassNotFoundException { args = new String []{"F:/IDEAWS/dashju/inputlog" , "F:/IDEAWS/dashju/outputlog2" }; Configuration conf = new Configuration (); Job job = Job.getInstance(conf); job.setJarByClass(LogDriver.class); job.setMapperClass(LogMapper.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(NullWritable.class); job.setNumReduceTasks(0 ); FileInputFormat.setInputPaths(job, new Path (args[0 ])); FileOutputFormat.setOutputPath(job, new Path (args[1 ])); job.waitForCompletion(true ); } }
MapReduce开发总结 在编写MapReduce程序时,需要考虑如下几个方面
(1)默认使用的实现类是: TextInputFormat
(2)TextInputFormat的功能逻辑是:一次读一行文本, 然后将该行的起始偏移量作为key,行内容作为value返回。
(3)KeyValueTextInputFormat每一行均为一条记录,被分隔符分割为key,value
。默认分隔符是tab ( \t
)。
(4)NineInputFormat按照指定的行数N来划分切片。
(5)CombineTextInputFormat可以把多个小文件合并成一个切片处理,提高处理效率。
(6)用户还可以自定义InputFormat。
2.逻辑处理接口: Mapper 用户根据业务需求实现其中三个方法: map()、setup()、 cleanup()。
3.Partitioner分区 (1)有默认实现HashPartitioner
,逻辑是根据key的哈希值和numReduces来返回一个分区号;
1 key.hashCode()&IntegerMAXVALUE % numReduces;
(2)如果业务上有特别的需求,可以自定义分区。
4.Comparable排序 (1)当我们用自定义的对象作为key来输出时,就必须要实现WritableComparable接口,重写其中的compareTo()方法。
(2)部分排序:对最终输出的每一个文件进行内部排序。
(3)全排序:对所有数据进行排序,通常只有一个Reduce。
(4)二次排序:排序的条件有两个。
5.Combiner合并 Combiner合并可以提高程序执行效率,减少IO传输。 但是使用时必须不能影响原有的业务处理结果。(汇总)
6.Reduce端分组: GroupingComparator 在Reduce端对key进行分组。 应用于:在接收的cey为bean对象时,想让一个或几个字段相同(全部字段比较不相同)的key进入到同一个reduce方法时,可以采用分组排序。
7.逻辑处理接口: Reducer 用户根据业务需求实现其中三个方法: reduce()、setp()、cleanup()
(1)默认实现类是TextOutputFormat,功能逻辑是:将每一个KV对, 向目标文本文件输出一行。
(2)将SequenceFileOutputFormat输出作为后续MapReduce任务的输入,这便是一种好的输出格式, 因为它的格式紧凑,很容易被压缩。
(3)用户还可以自定义OutputFormat。