总框架
准备map处理的输入数据 -》mapper处理-》Shuffle-》Reducer处理-》结果输出
数据输入
job提交源码
waitForCompletion()//(from driver.class)
submit();
// 1建立连接
connect();
// 1)创建提交Job的代理
new Cluster(getConfiguration());
// (1)判断是本地yarn还是远程
initialize(jobTrackAddr, conf);
// 2 提交job
submitter.submitJobInternal(Job.this, cluster)
// 1)创建给集群提交数据的Stag路径
Path jobStagingArea = JobSubmissionFiles.getStagingDir(cluster, conf);
// 2)获取jobid ,并创建Job路径
JobID jobId = submitClient.getNewJobID();
// 3)拷贝jar包到集群
copyAndConfigureFiles(job, submitJobDir);
rUploader.uploadFiles(job, jobSubmitDir);
// 4)计算切片,生成切片规划文件
writeSplits(job, submitJobDir);
maps = writeNewSplits(job, jobSubmitDir);
input.getSplits(job);
// 5)向Stag路径写XML配置文件
writeConf(conf, submitJobFile);
conf.writeXml(out);
// 6)提交Job,返回提交状态
status = submitClient.submitJob(jobId, submitJobDir.toString(), job.getCredentials());
切片机制
最终split个数=MapTask个数
FileInputFormat切片机制
切片大小默认等于blocksize大小,本地系统为32M,集群为128M
while(BytysRemaining/splitSize > SPLIT_SLOP) //>1,1
Ex:129m存两块(物理),129/128<1.1 切片(逻辑)切成一块
CombineTextInputFormat切片机制
<LongWritable,Text>
应用于大量小文件场景,通过将多个小文件在逻辑上集合到一个切片中,减少MapTask数量以提高效率。
CombineTextInputFormat.setMaxInputSplitSize(job, 4194304);// 4m
FileInputFormat 实现类
map阶段读入的数据,<key,value>
通过job.setInputFormatClass()设置
TextInputFormat(默认实现类)
<Longwirtable,Text>(该行其实字节偏移量偏移量,该行内容)
CombineTextInputFormat
KeyValueTextInputFormat
<Text,Text>(该行第一个单词,该行剩下内容)
// 设置切割符,默认为\t
conf.set(KeyValueLineRecordReader.KEY_VALUE_SEPERATOR, " ");
NLineInputFormat
每n行放入一个切片
<Longwirtable,Text>(行号,该行内容)
// 7设置每个切片InputSplit中划分三条记录
NLineInputFormat.setNumLinesPerSplit(job, 3);
// 8使用NLineInputFormat处理记录数
job.setInputFormatClass(NLineInputFormat.class);
自定义
ex:实现小文件合并,key为文件路径+名称,value为文件内容
<Text,BytesWritable>
步骤:
(1)自定义一个类己成FileInputFormat
// 定义类继承FileInputFormat
public class WholeFileInputformat extends FileInputFormat<Text, BytesWritable>{
@Override
protected boolean isSplitable(JobContext context, Path filename) {
return false;
}
@Override
public RecordReader<Text, BytesWritable> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
WholeRecordReader recordReader = new WholeRecordReader();
recordReader.initialize(split, context);
return recordReader;
}
(2)改写RecordReader,实现一次读取一个完整文件封装为KV
public class WholeRecordReader extends RecordReader<Text, BytesWritable>{
private Configuration configuration;
private FileSplit split;
private boolean isProgress= true;
private BytesWritable value = new BytesWritable();
private Text k = new Text();
@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
this.split = (FileSplit)split;
configuration = context.getConfiguration();
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
if (isProgress) {
// 1 定义缓存区
byte[] contents = new byte[(int)split.getLength()];
FileSystem fs = null;
FSDataInputStream fis = null;
try {
// 2 获取文件系统
Path path = split.getPath();
fs = path.getFileSystem(configuration);
// 3 读取数据
fis = fs.open(path);
// 4 读取文件内容
IOUtils.readFully(fis, contents, 0, contents.length);
// 5 输出文件内容
value.set(contents, 0, contents.length);
// 6 获取文件路径及名称
String name = split.getPath().toString();
// 7 设置输出的key值
k.set(name);
} catch (Exception e) {
}finally {
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 value;
}
@Override
public float getProgress() throws IOException, InterruptedException {
return 0;
}
@Override
public void close() throws IOException {
}
}
(3)输出时使用SequenceFileOutputFormat输出合并文件
// 7设置输入的inputFormat
job.setInputFormatClass(WholeFileInputformat.class);
// 8设置输出的outputFormat
job.setOutputFormatClass(SequenceFileOutputFormat.class);
MapTask阶段
1)Read阶段:MapTask通过用户编写的RecordReader,从输入InputSplit中解析出一个个key/value。
(2)Map阶段:该节点主要是将解析出的key/value交给用户编写map()函数处理,并产生一系列新的key/value。
public class WordcountMapper extends Mapper<LongWritable, Text, Text, IntWritable>{
//根据需要实现setup reduce close
//此为wordcount示例
Text k = new Text();
IntWritable v = new IntWritable(1);
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
// 1 获取一行
String line = value.toString();
// 2 切割
String[] words = line.split(" ");
// 3 输出
for (String word : words) {
k.set(word);
context.write(k, v);
}
}
}
(3)Collect收集阶段:在用户编写map()函数中,当数据处理完成后,一般会调用OutputCollector.collect()输出结果。在该函数内部,它会将生成的key/value分区(调用Partitioner),并写入一个环形内存缓冲区中。
(4)Spill阶段:即“溢写”,当环形缓冲区满后,MapReduce会将数据写到本地磁盘上,生成一个临时文件。需要注意的是,将数据写入本地磁盘之前,先要对数据进行一次本地排序,并在必要时对数据进行合并、压缩等操作。Sortandspill()
溢写阶段详情:
步骤1:利用快速排序算法对缓存区内的数据进行排序,排序方式是,先按照分区编号Partition进行排序,然后按照key进行排序。这样,经过排序后,数据以分区为单位聚集在一起,且同一分区内所有数据按照key有序。
步骤2:按照分区编号由小到大依次将每个分区中的数据写入任务工作目录下的临时文件output/spillN.out(N表示当前溢写次数)中。如果用户设置了Combiner,则写入文件之前,对每个分区中的数据进行一次聚集操作。
步骤3:将分区数据的元信息写到内存索引数据结构SpillRecord中,其中每个分区的元信息包括在临时文件中的偏移量、压缩前数据大小和压缩后数据大小。如果当前内存索引大小超过1MB,则将内存索引写到文件output/spillN.out.index中。
(5)Combine阶段:当所有数据处理完成后,MapTask对所有临时文件进行一次合并,以确保最终只会生成一个数据文件。mergeParts()
当所有数据处理完后,MapTask会将所有临时文件合并成一个大文件,并保存到文件output/file.out中,同时生成相应的索引文件output/file.out.index。
在进行文件合并过程中,MapTask以分区为单位进行合并。对于某个分区,它将采用多轮递归合并的方式。每轮合并io.sort.factor(默认10)个文件,并将产生的文件重新加入待合并列表中,对文件排序后,重复以上过程,直到最终得到一个大文件。
让每个MapTask最终只生成一个数据文件,可避免同时打开大量文件和同时读取大量小文件产生的随机读取带来的开销。
shuffle机制
Map方法之后,Reduce方法之前的数据处理过程称之为Shuffle。
Partition分区
将map后的结果按照条件输出到不同文件中(分区)
ex:手机号136、137、138、139开头都分别放到一个独立的4个文件中,其他开头的放到一个文件中。
public class ProvincePartitioner extends Partitioner<Text, FlowBean> {
@Override
public int getPartition(Text key, FlowBean value, int numPartitions) {
// 1 获取电话号码的前三位
String preNum = key.toString().substring(0, 3);
int partition = 4;
// 2 判断是哪个省
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;
}
}
// 8 指定自定义数据分区
job.setPartitionerClass(ProvincePartitioner.class);
// 9 同时指定相应数量的reduce task
job.setNumReduceTasks(5);
排序
排序概述
MapTask和ReduceTask均会对数据按照key进行排序,默认排序时按照字典顺序排序,实现方法为快速排序。
对于MapTask,它会将处理的结果暂时放到环形缓冲区,当环形缓冲区达到一定阈值后,再对缓冲区中的数据进行一次快速排序,并将有序数据溢写到磁盘上,而当数据处理完毕后,它会对所有文件进行归并排序。
对于ReduceTsk,它从每个MapTask上远程拷贝相应的数据文件(一个分区对应一个ReduceTask),如果文件大小超过一定阈值,则溢写到磁盘上,否则存储在内存中。如果磁盘上文件数目达到一定阈值,则进行一次归并排序以生成一个更大的文件。如果内存中文件大小或数目超过一定阈值,则进行一次合并后溢写到磁盘上。当所有数据拷贝完成后,ReduceTask统一对内存和磁盘上的所有数据进行一次归并排序。
排序分类
(1)部分排序
MapReduce根据输入记录的key对数据集排序,保证输出的每个文件内部有序
(2)全排序
最终输出只有一个文件,且文件内部有序,即设置只有一个ReduceTask。
处理大型文件时候效率低。
(3)分组排序(辅助排序)
在Reduce端对key进行分组。
应用场景:key为bean对象时,想让全部字段比较不相同,但某一属性相同的key进入同一个reduce方法。
(4)二次排序
自定义排序过程中,如果compareTo中的判断条件为两个即为二次排序
WirtableCompareable
bean对象做为key传输,需要实现WritableComparable接口重写compareTo方法,就可以实现排序。
@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;
}
GroupingComparator分组排序
对Reduce阶段的数据根据某一个字段或几个字段进行分组,再进入reduce方法,reduce方法按组读取,如果只读一次value,则只读每组的第一个kv。
分组排序步骤:
(1)自定义类继承WritableComparator
(2)重写compare()方法
(3)创建一个构造将比较对象的类传给父类
public class OrderGroupingComparator extends WritableComparator {
protected OrderGroupingComparator() {
super(OrderBean.class, true);
}
@Override
public int compare(WritableComparable a, WritableComparable b) {
OrderBean aBean = (OrderBean) a;
OrderBean bBean = (OrderBean) b;
int result;
if (aBean.getOrder_id() > bBean.getOrder_id()) {
result = 1;
} else if (aBean.getOrder_id() < bBean.getOrder_id()) {
result = -1;
} else {
result = 0;
}
return result;
}
}
job.setGroupingComparatorClass(OrderGroupingComparator.class);
ReduceTask阶段
(1)Copy阶段:ReduceTask从各个MapTask上远程拷贝一片数据,并针对某一片数据,如果其大小超过一定阈值,则写到磁盘上,否则直接放到内存中。
(2)Merge阶段:在远程拷贝数据的同时,ReduceTask启动了两个后台线程对内存和磁盘上的文件进行合并,以防止内存使用过多或磁盘上文件过多。
(3)Sort阶段:按照MapReduce语义,用户编写reduce()函数输入数据是按key进行聚集的一组数据。为了将key相同的数据聚在一起,Hadoop采用了基于排序的策略。由于各个MapTask已经实现对自己的处理结果进行了局部排序,因此,ReduceTask只需对所有数据进行一次归并排序即可。
(4)Reduce阶段:reduce()函数将计算结果写到HDFS上。
ReduceTask的并行度同样影响整个Job的执行并发度和执行效率,但与MapTask的并发数由切片数决定不同,ReduceTask数量的决定是可以直接手动设置(根据分区数or实际需要设置)。
public class WordcountReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
//根据需要实现setup reduce close
int sum;
IntWritable v = new IntWritable();
@Override
protected void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {
// 1 累加求和
sum = 0;
for (IntWritable count : values) {
sum += count.get();
}
// 2 输出
v.set(sum);
context.write(key,v);
}
}
// 默认值是1,手动设置为4
job.setNumReduceTasks(4);
Conbiner合并(可选)
MR程序中Mapper和Reducer之外的一种组件
其父类为Reducer
在每一个MapTask所在节点运行,Reduce是全局接受所有mapper输出的结果
意义:对于每一个MapTsk的输出进行局部汇总,减小网路传输量
应用前提:不能影响最终的业务逻辑
实现步骤:
自定义类己成Reducer,重写Reducer方法
public class WordcountCombiner extends Reducer<Text, IntWritable, Text,IntWritable>{
@Override
protected void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {
// 1 汇总操作
int count = 0;
for(IntWritable v :values){
count += v.get();
}
// 2 写出
context.write(key, new IntWritable(count));
}
}
job.setCombinerClass(WordcountCombiner.class);
数据输出(OutputFormat实现类)
TextOutputFormat
默认输出格式,每条记录写为文本行,写入的kv对可以为任意类型,会调用tostring方法将其转化为字符串。
SequentialFileOutputFormat
宜将其作为阶段性mapreduce的结果输出,因其格式紧凑,易压缩。
自定义OutputFormat类
类似于inputformat
public class FilterOutputFormat extends FileOutputFormat<Text, NullWritable>{
@Override
public RecordWriter<Text, NullWritable> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException {
// 创建一个RecordWriter
return new FilterRecordWriter(job);
}
}
public class FilterRecordWriter extends RecordWriter<Text, NullWritable> {
FSDataOutputStream atguiguOut = null;
FSDataOutputStream otherOut = null;
public FilterRecordWriter(TaskAttemptContext job) {
// 1 获取文件系统
FileSystem fs;
try {
fs = FileSystem.get(job.getConfiguration());
// 2 创建输出文件路径
Path a = new Path("e:/a.log");
Path o= new Path("e:/other.log");
// 3 创建输出流
atguiguOut = fs.create(atguiguPath);
otherOut = fs.create(otherPath);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void write(Text key, NullWritable value) throws IOException, InterruptedException {
// 判断是否包含“atguigu”输出到不同文件
if (key.toString().contains("a")) {
a.write(key.toString().getBytes());
} else {
o.write(key.toString().getBytes());
}
}
@Override
public void close(TaskAttemptContext context) throws IOException, InterruptedException {
// 关闭资源
IOUtils.closeStream(atguiguOut);
IOUtils.closeStream(otherOut); }
}
// 要将自定义的输出格式组件设置到job中
job.setOutputFormatClass(FilterOutputFormat.clas