[tim带你学]MapReduce阶段

分布式计算框架MapReduce

Hadoop组成 Hadoop HDFS:一个高可靠、高吞吐量的分布式文件系统,对海量数据的存储。
Hadoop MapReduce:一个分布式的资源调度和离线并行计算框架。
Hadoop Yarn:基于HDFS,用于作业调度和集群资源管理的框架。

在这里插入图片描述

A组

分布式并行计算框架MapReduce

什么是计算框架?

是指实现某项任务或某项工作从开始到结束的计算过程或流的结构。用于去解决或者处理某个复杂的计算问题。

在这里插入图片描述

什么是并行计算框架?

是指为更快的计算某项任务或某项工作,将计算程序分发到多台服务器上,使每个服务器计算总任务的一部分,多台服务器同时计算的框架。

在这里插入图片描述

什么是分布式计算?

分布式计算:是一种计算方法,是将该应用分解成许多小的部分,分配给多台计算机进行处理。这样可以节约整体计算时间,大大提高计算效率。

在这里插入图片描述

Hadoop为什么比传统技术方案快?

核心原因一:使用分布式存储。
核心原因二:使用分布式并行计算框架。

理解MapReduce思想

需求:有一个五层的图书馆,需要获取图书馆中一共有多少本书。只有一个人时,是能一本一本的数!工作量巨大,耗时较长。

分配五个人由你支配。此时你怎么支配?
五个人,每个人数一层的书量,最终将五个人的量汇总求和,就是图书馆中最终书的数量。

MapReduce的思想核心是“分而治之,先分后合”。即将一个大的、复杂的工作或任务,拆分成多个小的任务,并行处理,最终进行合并。适用于大量复杂的、时效性不高的任务处理场景(大规模离线数据处理场景)。即使是发布过论文实现分布式计算的谷歌也只是实现了这种思想,而不是自己原创。

MapReduce由两部分组成,分别是Map 和Reduce两部分。
Map负责“分”,即把复杂的任务分解为若干个“简单的任务”来并行处理。
可以进行拆分的前提是这些小任务可以并行计算,彼此间几乎没有依赖关系。例如前面例子中的分配每个人数一层楼。
Reduce负责“合”,即对map阶段的结果进行全局汇总。例如前面例子中将五个人的结果汇总。这两个阶段合起来正是MapReduce思想的体现。

MapReduce并行计算

HDFS存储数据时对大于128M的数据会进行数据切分,每128M一个数据块,数据块会分散、分布存储到HDFS。MapReduce在进行计算前会复制计算程序,每个数据块会分配一个独立的计算程序副本(MapTack)。计算时多个数据块几乎同时被读取并计算,但是计算程序完全相同。最终将各个计算程序计算的结果进行汇总(Reduce来汇总)

在这里插入图片描述

Hadoop -MapReduce设计构思

MapReduce是一个分布式运算程序的编程框架,核心功能是将用户编写的业务逻辑代码和自带默认组件整合成一个完整的分布式运算程序,并发运行在Hadoop集群上。
既然是做计算的框架,那么表现形式就是有个输入(input),MapReduce操作这个输入(input),通过本身定义好的计算模型,得到一个输出(output)。
Hadoop MapReduce构思体现在如下的三个方面:

l 如何应对大数据处理:分而治之
对相互间不具有计算依赖关系的大数据,实现并行最自然的办法就是采取分而治之的策略。并行计算的第一个重要问题是如何划分计算任务或者计算数据以便对划分的子任务或数据块同时进行计算。不可分拆的计算任务或相互间有依赖关系的数据无法进行并行计算!

l 构建抽象模型:Map和Reduce

MapReduce借鉴了函数式语言中的思想,用Map和Reduce两个函数提供了高层的并行编程抽象模型。
Map: 对一组数据元素进行某种重复式的处理;
Reduce: 对Map的中间结果进行某种进一步的结果整理。
MapReduce中定义了如下的Map和Reduce两个抽象的编程接口,由用户去编程实现:
map: [k1,v1] → [(k2,v2)]
reduce: [k2, {v2,…}] → [k3, v3]

在这里插入图片描述

在这里插入图片描述
Map和Reduce为程序员提供了一个清晰的操作接口抽象描述。通过以上两个编程接口,大家可以看出MapReduce处理的数据类型是<key,value>键值对。

l 统一构架,隐藏系统层细节

如何提供统一的计算框架,如果没有统一封装底层细节,那么程序员则需要考虑诸如数据存储、划分、分发、结果收集、错误恢复等诸多细节;为此,MapReduce设计并提供了统一的计算框架,为程序员隐藏了绝大多数系统层面的处理细节。

MapReduce最大的亮点在于通过抽象模型和计算框架把需要做什么(what need to do)与具体怎么做(how to do)分开了,为程序员提供一个抽象和高层的编程接口和框架。程序员仅需要关心其应用层的具体计算问题,仅需编写少量的处理应用本身计算问题的程序代码。如何具体完成这个并行计算任务所相关的诸多系统层细节被隐藏起来,交给计算框架去处理:从分布代码的执行,到大到数千小到单个节点集群的自动调度使用。

MapReduce编程初体验

需求:在给定的文本文件中统计输出每一个单词出现的总次数
在这里插入图片描述

项目POM文件~

略过

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

错误提醒:如果遇到这个错误,Caused by: org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.security.AccessControlException): Permission denied: user=admin, access=WRITE, inode="/":root:supergroup:drwxr-xr-x直接将hdfs-site.xml当中的权限关闭即可~

在这里插入图片描述

重启hdfs集群,重新运行代码编写完毕后,将代码打成jar包放到服务器上去运行运行命令如下~

hadoop jar hadoop_hdfs_operate-1.0-SNAPSHOT.jar cn.itcast.hdfs.demo1.JobMain~

在这里插入图片描述

MapReduce编程规范及示例编写~

编程规范~

mapReduce编程模型的总结:~

事实上MapReduce的开发一共有八个步骤其中map阶段分为2个步骤,shuffle阶段4个步骤,reduce阶段分为2个步骤~

Map阶段2个步骤~

第一步:设置inputFormat类,将数据切分成key,value对,输入到第二步
第二步:自定义map逻辑,处理第一步的输入数据,然后转换成新的key,value对进行输出~

在这里插入图片描述

shuffle阶段4个步骤(可以全部不用管)~

第三步:对输出的key,value对进行分区。相同key的数据发送到同一个reduce里面去,相同key合并,value形成一个集合
第四步:对不同分区的数据按照相同的key进行排序
第五步:对分组后的数据进行规约(combine操作),降低数据的网络拷贝(可选步骤)
第六步:对排序后的额数据进行分组,分组的过程中,将相同key的value放到一个集合当中~

在这里插入图片描述

reduce阶段2个步骤~

在这里插入图片描述

在这里插入图片描述

5、Mapper以及Reducer抽象类介绍~

为了开发MapReduce程序,一共可以分为以上八个步骤,其中每个步骤都是一个class类,通过job对象将程序组装成一个任务提交即可。为了简化MapReduce程序的开发,每一个步骤的class类,都有一个既定的父类,直接继承即可,因此可以大大简化MapReduce程序的开发难度,也可以快速的实现功能开发。
MapReduce编程当中,其中最重要的两个步骤就是Mapper类和Reducer类~

1、 Mapper抽象类的基本介绍~

在hadoop2.x当中Mapper类是一个抽象类,工程师只需要覆写一个java类,继承自Mapper类即可,然后重写里面的一些方法,就可以实现特定的功能,接下来介绍一下Mapper类当中比较重要的四个方法~

1、setup方法:Mapper类当中的初始化方法,程序中一些对象的初始化工作都可以放到这个方法里面来实现~

2、map方法:读取的每一行数据,都会来调用一次map方法,这个方法也是最重要的方法,可以通过这个方法来实现每一条数据的处理。~

3、cleanup方法:在整个maptask执行完成之后,会马上调用cleanup方法,这个方法主要是做一些清理工作,例如连接的断开,资源的关闭等等~

4、run方法:如果需要更精细的控制整个MapTask的执行,那么可以覆写这个方法,实现对所有的MapTask更精确的操作控制~

2、Reducer抽象类基本介绍~

同样的道理,在hadoop2.x当中,reducer类也是一个抽象类,抽象类允许工程师可以继承这个抽象类之后,重新覆写抽象类当中的方法,实现逻辑的自定义控制。接下来也来介绍一下Reducer抽象类当中的四个抽象方法~

1、setup方法: 在ReduceTask初始化之后马上调用,一些对象的初始化工作,可以在这个类当中实现~

2、reduce方法:所有从MapTask发送过来的数据,都会调用reduce方法,这个方法也是reduce当中最重要的方法,可以通过这个方法实现数据的处理~

3、cleanup方法:在整个ReduceTask执行完成之后,会马上调用cleanup方法,这个方法主要就是在reduce阶段做一些清理工作,例如连接的断开,资源的关闭等等~

4、run方法:如果需要更精细的控制整个ReduceTask的执行,那么可以覆写这个方法,实现对所有的ReduceTask更精确的操作控制~

6、手写WordCount示例编写~

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2、MapReduce当中的计数器

计数器是收集作业统计信息的有效手段之一,用于质量控制或应用级统计。计数器还可辅助诊断系统故障。如果需要将日志信息传输到map 或reduce 任务, 更好的方法通常是看能否用一个计数器值来记录某一特定事件的发生。对于大型分布式作业而言,使用计数器更为方便。除了因为获取计数器值比输出日志更方便,还有根据计数器值统计特定事件的发生次数要比分析一堆日志文件容易得多。

在这里插入图片描述

每次mapreduce执行完成之后,都会看到一些日志记录出来,其中最重要的一些日志记录如下截图

在这里插入图片描述
自定义计数器第一种方式定义计数器,通过context上下文对象可以获取计数器,进行记录通过context上下文对象,在map端使用计数器进行统计

在这里插入图片描述
在这里插入图片描述
第二种方式定义计数器通过enum枚举类型来定义计数器统计reduce端数据的输入的key有多少个,对应的value有多少个
在这里插入图片描述

3、MapReduce的combiner

每一个 map 都可能会产生大量的本地输出,Combiner 的作用就是对 map 端的输出先做一次合并,以减少在 map 和 reduce 节点之间的数据传输量,以提高网络IO 性能,是 MapReduce 的一种优化手段之一。
combiner 是 MR 程序中 Mapper 和 Reducer 之外的一种组件
combiner 组件的父类就是 Reducer
combiner 和 reducer 的区别在于运行的位置:
Combiner 是在每一个 maptask 所在的节点运行 Reducer 是接收全局所有 Mapper 的输出结果;l combiner 的意义就是对每一个 maptask 的输出进行局部汇总,以减小网络传输量
未使用combiner的网络开销
在这里插入图片描述
具体实现步骤:
1、自定义一个 combiner 继承 Reducer,重写 reduce 方法
2、在 job 中设置: job.setCombinerClass(CustomCombiner.class)

combiner 能够应用的前提是不能影响最终的业务逻辑,而且,combiner 的输出 kv 应该跟 reducer 的输入 kv 类型要对应起来

5、MapReduce综合练习之上网流量统计

需求一:统计求和

统计每个手机号的上行流量总和,下行流量总和,上行总流量之和,下行总流量之和分析:以手机号码作为key值,上行流量,下行流量,上行总流量,下行总流量四个字段作为value值,然后以这个key,和value作为map阶段的输出,reduce阶段的输入

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

需求二:上行流量倒序排序(递减排序)

分析,以需求一的输出数据作为排序的输入数据,自定义FlowBean,以FlowBean为map输出的key,以手机号作为Map输出的value,因为MapReduce程序会对Map阶段输出的key进行排序

第一步:定义FlowBean实现WritableComparable实现比较排序

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

需求三:手机号码分区

在需求一的基础上,继续完善,将不同的手机号分到不同的数据文件的当中去,需要自定义分区来实现,这里自定义来模拟分区,将以下数字开头的手机号进行分开

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

C组

1、MapTask运行机制详解以及Map任务的并行度

在这里插入图片描述
整个Map阶段流程大体如上图所示。简单概述:inputFile通过split被逻辑切分为多个split文件,通过Record按行读取内容给map(用户自己实现的)进行处理,数据被map处理结束之后交给OutputCollector收集器,对其结果key进行分区(默认使用hash分区),然后写入buffer,每个map task都有一个内存缓冲区,存储着map的输出结果,当缓冲区快满的时候需要将缓冲区的数据以一个临时文件的方式存放到磁盘,当整个map task结束后再对磁盘中这个map task产生的所有临时文件做合并,生成最终的正式输出文件,然后等待reduce task来拉数据。

在这里插入图片描述
1、首先,读取数据组件InputFormat(默认TextInputFormat)会通过getSplits方法对输入目录中文件进行逻辑切片规划得到splits,有多少个split就对应启动多少个MapTask。默认情况下split与block的对应关系默认是一对一。

2、将输入文件切分为splits之后,由RecordReader对象(默认LineRecordReader)进行读取,以\n作为分隔符,读取一行数据,返回<key,value>。Key表示每行首字符偏移值,value表示这一行文本内容。

3、读取split返回<key,value>,进入用户自己继承的Mapper类中,执行用户重写的map函数。RecordReader读取一行用户重写的map调用一次,并输出一个<key,value>。

4、Map输出的数据会写入内存,内存中这片区域叫做环形缓冲区,缓冲区的作用是批量收集map结果,减少磁盘IO的影响。key/value对以及Partition的结果都会被写入缓冲区。当然写入之前,key与value值都会被序列化成字节数组。环形缓冲区其实是一个数组,数组中存放着key、value的序列化数据和key、value的元数据信息,包括partition、key的起始位置、value的起始位置以及value的长度。环形结构是一个抽象概念。缓冲区是有大小限制,默认是100MB。当map task的输出结果很多时,就可能会撑爆内存,所以需要在一定条件下将缓冲区中的数据临时写入磁盘,然后重新利用这块缓冲区。这个从内存往磁盘写数据的过程被称为Spill,中文可译为溢写。这个溢写是由单独线程来完成,不影响往缓冲区写map结果的线程。溢写线程启动时不应该阻止map的结果输出,所以整个缓冲区有个溢写的比例spill.percent。这个比例默认是0.8,也就是当缓冲区的数据已经达到阈值(buffer size * spill percent = 100MB * 0.8 = 80MB),溢写线程启动,锁定这80MB的内存,执行溢写过程。Map task的输出结果还可以往剩下的20MB内存中写,互不影响。

5、合并溢写文件:Ø每次溢写会在磁盘上生成一个临时文件(写之前判断是否有combiner),如果map的输出结果真的很大,有多次这样的溢写发生,磁盘上相应的就会有多个临时文件存在。当整个数据处理结束之后开始对磁盘中的临时文件进行merge合并,因为最终的文件只有一个,写入磁盘,并且为这个文件提供了一个索引文件,以记录每个reduce对应数据的偏移量。至此map整个阶段结束。

mapTask的一些基础设置配置(mapred-site.xml当中社会)

在这里插入图片描述

2、ReduceTask 工作机制以及reduceTask的并行度

Reduce大致分为copy、sort、reduce三个阶段,重点在前两个阶段。copy阶段包含一个eventFetcher来获取已完成的map列表,由Fetcher线程去copy数据,在此过程中会启动两个merge线程,分别为inMemoryMerger和onDiskMerger,分别将内存中的数据merge到磁盘和将磁盘中的数据进行merge。待数据copy完成之后,copy阶段就完成了,开始进行sort阶段,sort阶段主要是执行finalMerge操作,纯粹的sort阶段,完成之后就是reduce阶段,调用用户定义的reduce函数进行处理。

在这里插入图片描述

详细步骤:

1、Copy阶段,简单地拉取数据。Reduce进程启动一些数据copy线程(Fetcher),通过HTTP方式请求maptask获取属于自己的文件。

2、Merge阶段。这里的merge如map端的merge动作,只是数组中存放的是不同map端copy来的数值。Copy过来的数据会先放入内存缓冲区中,这里的缓冲区大小要比map端的更为灵活。merge有三种形式:内存到内存;内存到磁盘;磁盘到磁盘。默认情况下第一种形式不启用。当内存中的数据量到达一定阈值,就启动内存到磁盘的merge。与map 端类似,这也是溢写的过程,这个过程中如果你设置有Combiner,也是会启用的,然后在磁盘中生成了众多的溢写文件。第二种merge方式一直在运行,直到没有map端的数据时才结束,然后启动第三种磁盘到磁盘的merge方式生成最终的文件。

3、合并排序。把分散的数据合并成一个大的数据后,还会再对合并后的数据排序。

4、对排序后的键值对调用reduce方法,键相等的键值对调用一次reduce方法,每次调用会产生零个或者多个键值对,最后把这些输出的键值对写入到HDFS文件中。

MapReduce总体工作机制

1、 map逻辑完之后,将map的每条结果通过context.write进行collect数据收集。在collect中,会先对其进行分区处理,默认使用HashPartitioner。MapReduce提供Partitioner接口,它的作用就是根据key或value及reduce的数量来决定当前的这对输出数据最终应该交由哪个reduce task处理。默认对key hash后再以reduce task数量取模。默认的取模方式只是为了平均reduce的处理能力,如果用户自己对Partitioner有需求,可以订制并设置到job上。

6、当溢写线程启动后,需要对这80MB空间内的key做排序(Sort)。排序是MapReduce模型默认的行为,这里的排序也是对序列化的字节做的排序。 如果job设置过Combiner,那么现在就是使用Combiner的时候了。将有相同key的key/value对的value加起来,减少溢写到磁盘的数据量。Combiner会优化MapReduce的中间结果,所以它在整个模型中会多次使用。哪些场景才能使用Combiner呢?从这里分析,Combiner的输出是Reducer的输入,Combiner绝不能改变最终的计算结果。Combiner只应该用于那种Reduce的输入key/value与输出key/value类型完全一致,且不影响最终结果的场景。比如累加,最大值等(求平均值绝不能用Combiner)。Combiner的使用一定得慎重,如果用好,它对job执行效率有帮助,反之会影响reduce的最终结果。

3、MapReduceshuffle过程

map阶段处理的数据如何传递给reduce阶段,是MapReduce框架中最关键的一个流程,这个流程就叫shuffle。

shuffle: 洗牌、发牌——(核心机制:数据分区,排序,分组,ComBine,合并等过程)。

在这里插入图片描述

shuffle是Mapreduce的核心,它分布在Mapreduce的map阶段和reduce阶段。一般把从Map产生输出开始到Reduce取得数据作为输入之前的过程称作shuffle。

维度一,流程维度回顾。从Map输出到Reduce输入。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

维度二,内存维度回顾。从Map输出到Reduce输入。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
1).Collect阶段:将MapTask的结果输出到默认大小为100M的环形缓冲区,保存的是key/value,Partition分区信息等。

2).Spill阶段:当内存中的数据量达到一定的阀值的时候,就会将数据写入本地磁盘,在将数据写入磁盘之前需要对数据进行一次排序的操作,如果配置了combiner,还会将有相同分区号和key的数据进行排序。

3).Merge阶段:把所有溢出的临时文件进行一次合并操作,以确保一个MapTask最终只产生一个中间数据文件。

4).Copy阶段:ReduceTask启动Fetcher线程到已经完成MapTask的节点上复制一份属于自己的数据,这些数据默认会保存在内存的缓冲区中,当内存的缓冲区达到一定的阀值的时候,就会将数据写到磁盘之上。

5).Merge阶段:在ReduceTask远程复制数据的同时,会在后台开启两个线程对内存到本地的数据文件进行合并操作。

6).Sort阶段:在对数据进行合并的同时,会进行排序操作,由于MapTask阶段已经对数据进行了局部的排序,ReduceTask只需保证Copy的数据的最终整体有效性即可。

Shuffle中的缓冲区大小会影响到mapreduce程序的执行效率,原则上说,缓冲区越大,磁盘io的次数越少,执行速度就越快

缓冲区的大小可以通过参数调整, 参数:mapreduce.task.io.sort.mb 默认100M

4、shuffle阶段数据的压缩机制

在shuffle阶段,可以看到数据通过大量的拷贝,从map阶段输出的数据,都要通过网络拷贝,发送到reduce阶段,这一过程中,涉及到大量的网络IO,如果数据能够进行压缩,那么数据的发送量就会少得多,那么如何配置hadoop的文件压缩呢,以及hadoop当中的文件压缩支持哪些压缩算法呢??接下来一一细看

MapReduce的执行流程

为什么要配置压缩:

在这里插入图片描述

1、hadoop当中支持的压缩算法

文件压缩有两大好处,节约磁盘空间,加速数据在网络和磁盘上的传输前面hadoop的版本经过重新编译之后,可以看到hadoop已经支持所有的压缩格式了,剩下的问题就是该如何选择使用这些压缩格式来对MapReduce程序进行压缩可以使用bin/hadoop checknative 来查看编译之后的hadoop支持的各种压缩,如果出现openssl为false,那么就在线安装一下依赖包

bin/hadoop checknative
yum install openssl-devel

在这里插入图片描述

hadoop支持的压缩算法

在这里插入图片描述
各种压缩算法对应使用的java类

在这里插入图片描述
常见的压缩速率比较

在这里插入图片描述
snappy比以上压缩算法都要快

如何开启压缩:

方式一:在代码中进行设置压缩

在这里插入图片描述
方式二:配置全局的MapReduce压缩

修改mapred-site.xml配置文件,然后重启集群,以便对所有的mapreduce任务进行压缩

map输出数据进行压缩

<property>         
 <name>mapreduce.map.output.compress</name>      
     <value>true</value></property><property>     
         <name>mapreduce.map.output.compress.codec</name>         
         <value>org.apache.hadoop.io.compress.SnappyCodec</value>
</property>

reduce输出数据进行压缩

<property>      
 <name>mapreduce.output.fileoutputformat.compress</name>   
     <value>true</value></property><property>         
     <name>mapreduce.output.fileoutputformat.compress.type</name>     
        <value>RECORD</value></property> <property>        
        <name>mapreduce.output.fileoutputformat.compress.codec</name>        
        <value>org.apache.hadoop.io.compress.SnappyCodec</value> 
        </property>

所有节点都要修改mapred-site.xml,修改完成之后记得重启集群

2、使用hadoop的snappy压缩来对数据进行压缩

第一步:代码中添加配置

这里通过修改代码的方式来实现数据的压缩
map阶段输出压缩配置

在这里插入图片描述

在这里插入图片描述
第二步:重新打包测试mr程序

会发现MR运行之后的输出文件都变成了以.snappy的压缩文件

5、reduce端join与map端join算法实现

1、reduce端join算法实现

1、需求:
订单数据表t_order:

在这里插入图片描述

假如数据量巨大,两表的数据是以文件的形式存储在HDFS中,需要用mapreduce程序来实现一下SQL查询运算:

select a.id,a.date,b.name,b.category_id,b.price from t_order a join t_product b on a.pid = b.id

2、实现机制:
通过将关联的条件作为map输出的key,将两表满足join条件的数据并携带数据所来源的文件信息,发往同一个reduce task,在reduce中进行数据的串联

第一步:定义OrderBean

public class OrderJoinBean implements Writable {
    private String id;
    private String date;
    private String pid;
    private String amount;
    private String name;
    private String categoryId;
    private String price;
    @Override
    public String toString() {
        return id+"\t"+date+"\t"+pid+"\t"+amount+"\t"+name+"\t"+categoryId+"\t"+price;
    }
    public OrderJoinBean() {
    }

    public OrderJoinBean(String id, String date, String pid, String amount, String name, String categoryId, String price) {
        this.id = id;
        this.date = date;
        this.pid = pid;
        this.amount = amount;
        this.name = name;
        this.categoryId = categoryId;
        this.price = price;
    }
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getPid() {
        return pid;
    }
    public void setPid(String pid) {
        this.pid = pid;
    }
    public String getAmount() {
        return amount;
    }
    public void setAmount(String amount) {
        this.amount = amount;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCategoryId() {
        return categoryId;
    }
    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
    }
    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    @Override
    public void write(DataOutput out) throws IOException {
        out.writeUTF(id+"");
        out.writeUTF(date+"");
        out.writeUTF(pid+"");
        out.writeUTF(amount+"");
        out.writeUTF(name+"");
        out.writeUTF(categoryId+"");
        out.writeUTF(price+"");
    }

    @Override
    public void readFields(DataInput in) throws IOException {
       this.id =  in.readUTF();
        this.date =  in.readUTF();
        this.pid =  in.readUTF();
        this.amount =  in.readUTF();
        this.name =  in.readUTF();
        this.categoryId =  in.readUTF();
        this.price =  in.readUTF();

    }
}

第二步:定义map类

public class OrderJoinMap extends Mapper<LongWritable,Text,Text,OrderJoinBean> {
    private OrderJoinBean orderJoinBean = new OrderJoinBean();
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
       //通过获取文件名来区分两个不同的文件
        String[] split = value.toString().split(",");
        FileSplit inputSplit = (FileSplit) context.getInputSplit();
        String name = inputSplit.getPath().getName();
        System.out.println("获取文件名为"+name);
        if(name.contains("orders")){
            //订单数据
            orderJoinBean.setId(split[0]);
            orderJoinBean.setDate(split[1]);
            orderJoinBean.setPid(split[2]);
            orderJoinBean.setAmount(split[3]);
            context.write(new Text(split[2]),orderJoinBean);
        }else{
            //商品数据
            orderJoinBean.setName(split[1]);
            orderJoinBean.setCategoryId(split[2]);
            orderJoinBean.setPrice(split[3]);
            context.write(new Text(split[0]),orderJoinBean);
        }

    }
}

第三步:自定义reduce类

public class OrderJoinReduce extends Reducer<Text,OrderJoinBean,OrderJoinBean,NullWritable> {
    private OrderJoinBean orderJoinBean;
    @Override
    protected void reduce(Text key, Iterable<OrderJoinBean> values, Context context) throws IOException, InterruptedException {
         orderJoinBean = new OrderJoinBean();
        for (OrderJoinBean value : values) {
            System.out.println(value.getId());
            //相同的key的对象都发送到了这里,在这里将数据拼接完整
          if(null !=value.getId() && !value.getId().equals("null") ){
              orderJoinBean.setId(value.getId());
              orderJoinBean.setDate(value.getDate());
              orderJoinBean.setPid(value.getPid());
              orderJoinBean.setAmount(value.getAmount());
          }else{
              orderJoinBean.setName(value.getName());
              orderJoinBean.setCategoryId(value.getCategoryId());
              orderJoinBean.setPrice(value.getPrice());
          }
        }
        context.write(orderJoinBean,NullWritable.get());
    }
}

第四步:开发main方法入口

public class OrderJoinMain extends Configured implements Tool {
    @Override
    public int run(String[] args) throws Exception {
        Job job = Job.getInstance(super.getConf(), OrderJoinMain.class.getSimpleName());

        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat.addInputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\4、大数据离线第四天\\map端join\\input"));
        job.setMapperClass(OrderJoinMap.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(OrderJoinBean.class);
        job.setReducerClass(OrderJoinReduce.class);
        job.setOutputKeyClass(OrderJoinBean.class);
        job.setOutputValueClass(NullWritable.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        TextOutputFormat.setOutputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\4、大数据离线第四天\\map端join\\out"));
        boolean b = job.waitForCompletion(true);
        return b?0:1;
    }

    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Configuration(),new OrderJoinMain(),args);
    }
}

缺点:这种方式中,join的操作是在reduce阶段完成,reduce端的处理压力太大,map节点的运算负载则很低,资源利用率不高,且在reduce阶段极易产生数据倾斜

解决方案: map端join实现方式

2 map端join算法实现

1、原理阐述适用于关联表中有小表的情形;可以将小表分发到所有的map节点,这样,map节点就可以在本地对自己所读到的大表数据进行join并输出最终结果,可以大大提高join操作的并发度,加快处理速度

2、实现示例
–先在mapper类中预先定义好小表,进行join

–引入实际场景中的解决方案:

一次加载数据库或者用

第一步:定义mapJoin

public class JoinMap extends Mapper<LongWritable,Text,Text,Text> {
    HashMap<String,String> b_tab = new HashMap<String, String>();
    String line = null;
    /*
    map端的初始化方法当中获取缓存文件,一次性加载到map当中来
     */
    @Override
    public void setup(Context context) throws IOException, InterruptedException {
        //这种方式获取所有的缓存文件
     //   URI[] cacheFiles1 = DistributedCache.getCacheFiles(context.getConfiguration());
        Path[] localCacheFiles = DistributedCache.getLocalCacheFiles(context.getConfiguration());
        URI[] cacheFiles = DistributedCache.getCacheFiles(context.getConfiguration());
        FileSystem fileSystem = FileSystem.get(cacheFiles[0], context.getConfiguration());
        FSDataInputStream open = fileSystem.open(new Path(cacheFiles[0]));
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(open));
        while ((line = bufferedReader.readLine())!=null){
            String[] split = line.split(",");
            b_tab.put(split[0],split[1]+"\t"+split[2]+"\t"+split[3]);
        }
        fileSystem.close();
        IOUtils.closeStream(bufferedReader);
    }

    @Override
    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //这里读的是这个map task所负责的那一个切片数据(在hdfs上)
        String[] fields = value.toString().split(",");
        String orderId = fields[0];
        String date = fields[1];
        String pdId = fields[2];
        String amount = fields[3];
        //获取map当中的商品详细信息
        String productInfo = b_tab.get(pdId);
        context.write(new Text(orderId), new Text(date + "\t" + productInfo+"\t"+amount));
    }
}

第二步:定义程序运行main方法

public class MapSideJoin extends Configured implements Tool {
    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = super.getConf();
        //注意,这里的缓存文件的添加,只能将缓存文件放到hdfs文件系统当中,放到本地加载不到
        DistributedCache.addCacheFile(new URI("hdfs://192.168.100.129:8020/cachefile/pdts.txt"),conf);
        Job job = Job.getInstance(conf, MapSideJoin.class.getSimpleName());
        job.setJarByClass(MapSideJoin.class);
        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat.addInputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\4、大数据离线第四天\\map端join\\map_join_iput"));
        job.setMapperClass(JoinMap.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        TextOutputFormat.setOutputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\4、大数据离线第四天\\map端join\\map_join_output")) ;
        boolean b = job.waitForCompletion(true);
        return b?0:1;
    }
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        ToolRunner.run(configuration,new MapSideJoin(),args);

    }
}

6、社交粉丝数据分析

在这里插入图片描述

求出哪些人两两之间有共同好友,及他俩的共同好友都有谁?
解题思路:

在这里插入图片描述
在这里插入图片描述

第一步:代码实现

public class ComonsFriendsStepOne  extends Configured implements Tool {
    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = super.getConf();
        Job job = Job.getInstance(conf, ComonsFriendsStepOne.class.getSimpleName());
        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat.addInputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\5、大数据离线第五天\\共同好友\\input"));
        job.setMapperClass(ComonsFriendsStepOneMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setReducerClass(ComonsFriendsStepOneReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        TextOutputFormat.setOutputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\5、大数据离线第五天\\共同好友\\output"));
        boolean b = job.waitForCompletion(true);
        return b?0:1;
    }
    public  static class ComonsFriendsStepOneMapper  extends Mapper<LongWritable,Text,Text,Text>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] split = value.toString().split(":");
            String person = split[0];
            String[] friends = split[1].split(",");
            for (String friend : friends) {
                context.write(new Text(friend),new Text(person));
            }
        }
    }
    public static class ComonsFriendsStepOneReducer extends Reducer<Text,Text,Text,Text>{
        @Override
        protected void reduce(Text friend, Iterable<Text> persons, Context context) throws IOException, InterruptedException {
            StringBuffer buffer = new StringBuffer();
            for (Text person : persons) {
                buffer.append(person).append("-");
            }
            context.write(friend,new Text(buffer.toString()));
        }
    }
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        ToolRunner.run(configuration,new ComonsFriendsStepOne(),args);
    }
}

第二步:代码实现

public class ComonsFriendsStepTwo extends Configured implements Tool {
    @Override
    public int run(String[] args) throws Exception {

        Job job = Job.getInstance(super.getConf(), ComonsFriendsStepTwo.class.getSimpleName());
        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat.addInputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\5、大数据离线第五天\\共同好友\\output"));
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setMapperClass(ComonsFriendStepTwoMapper.class);
        job.setReducerClass(ComonsFriendStepTwoReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        job.setOutputFormatClass(TextOutputFormat.class);
        TextOutputFormat.setOutputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\5、大数据离线第五天\\共同好友\\outstep2"));
        boolean b = job.waitForCompletion(true);
        return b?0:1;
    }
    public  static  class ComonsFriendStepTwoMapper  extends Mapper<LongWritable,Text,Text,Text>{

        /**
         * A   F-D-O-I-H-B-K-G-C-
         * B   E-A-J-F-
         * C   K-A-B-E-F-G-H-
         */
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] split = value.toString().split("\t");
            String friends = split[0];
            String[] persons = split[1].split("-");
            //排序,避免c-b  与b-c  这样的情况出现
            Arrays.sort(persons);
            for(int i =0;i< persons.length -1 ;i++){
                for(int j = i+1;j<persons.length;j++){
                    context.write(new Text(persons[i]+"-"+persons[j]),new Text(friends));
                }

            }
        }
    }
    public static class ComonsFriendStepTwoReducer extends Reducer<Text,Text,Text,Text>{
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            StringBuffer buffer = new StringBuffer();
            for (Text value : values) {
                buffer.append(value.toString()+"\t");
            }
            context.write(key,new Text(buffer.toString()));
        }
    }
    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Configuration(),new ComonsFriendsStepTwo(),args);
    }
}

7、倒排索引建立

在这里插入图片描述
代码实现

public class IndexCreate extends Configured implements Tool {
    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Configuration(),new IndexCreate(),args);
    }
    @Override
    public int run(String[] args) throws Exception {
        Job job = Job.getInstance(super.getConf(), IndexCreate.class.getSimpleName());
        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat.addInputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\5、大数据离线第五天\\倒排索引\\input"));
        job.setMapperClass(IndexCreateMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setReducerClass(IndexCreateReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        TextOutputFormat.setOutputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\5、大数据离线第五天\\倒排索引\\outindex"));
        boolean bool = job.waitForCompletion(true);
        return bool?0:1;
    }
    public static class IndexCreateMapper extends Mapper<LongWritable,Text,Text,IntWritable>{
        Text text = new Text();
        IntWritable v = new IntWritable(1);
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            //获取文件切片
            FileSplit fileSplit  = (FileSplit) context.getInputSplit();
            //通过文件切片获取文件名
            String name = fileSplit.getPath().getName();
            String line = value.toString();
            String[] split = line.split(" ");
            //输出 单词--文件名作为key  value是1
            for (String word : split) {
               text.set(word+"--"+name);
                context.write(text,v);
            }
        }
    }
    public static class IndexCreateReducer extends Reducer<Text,IntWritable,Text,IntWritable>{
        IntWritable value = new IntWritable();
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int count = 0;
            for (IntWritable value : values) {
                count += value.get();
            }
            value.set(count);
            context.write(key,value);
        }
    }
}

8、自定义inputFormat合并小文件

在这里插入图片描述

自定义InputFromat

public class WholeFileInputFormat extends FileInputFormat<NullWritable, BytesWritable>{
   /*
   直接返回文件不可切割,保证一个文件是一个完整的一行
    */
   @Override
   protected boolean isSplitable(JobContext context, Path file) {
      return false;
   }
   @Override
   public RecordReader<NullWritable, BytesWritable> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException,InterruptedException {
      WholeFileRecordReader reader = new WholeFileRecordReader();
      reader.initialize(split, context);
      return reader;
   }
}

自定义RecordReader

/**
 * 
 * RecordReader的核心工作逻辑:
 * 通过nextKeyValue()方法去读取数据构造将返回的key   value
 * 通过getCurrentKey 和 getCurrentValue来返回上面构造好的key和value
 * 
 * 
 * @author
 *
 */
public class WholeFileRecordReader extends RecordReader<NullWritable, BytesWritable> {
   private FileSplit fileSplit;
   private Configuration conf;
   private BytesWritable value = new BytesWritable();
   private boolean processed = false;
   @Override
   public void initialize(InputSplit split, TaskAttemptContext context)
         throws IOException, InterruptedException {
      this.fileSplit = (FileSplit) split;
      this.conf = context.getConfiguration();
   }
   @Override
   public boolean nextKeyValue() throws IOException, InterruptedException {
      if (!processed) {
         byte[] contents = new byte[(int) fileSplit.getLength()];
         Path file = fileSplit.getPath();
         FileSystem fs = file.getFileSystem(conf);
         FSDataInputStream in = null;
         try {
            in = fs.open(file);
            IOUtils.readFully(in, contents, 0, contents.length);
            value.set(contents, 0, contents.length);
         } finally {
            IOUtils.closeStream(in);
         }
         processed = true;
         return true;
      }
      return false;
   }
   @Override
   public NullWritable getCurrentKey() throws IOException,
         InterruptedException {
      return NullWritable.get();
   }
   @Override
   public BytesWritable getCurrentValue() throws IOException,
         InterruptedException {
      return value;
   }
   @Override
   public float getProgress() throws IOException {
      return processed ? 1.0f : 0.0f;
   }
   @Override
   public void close() throws IOException {
   }
}

定义mapreduce处理流程

public class SmallFilesToSequenceFileConverter extends Configured implements Tool {
   static class SequenceFileMapper extends
         Mapper<NullWritable, BytesWritable, Text, BytesWritable> {
      private Text filenameKey;
      @Override
      protected void setup(Context context) throws IOException,
            InterruptedException {
         InputSplit split = context.getInputSplit();
         Path path = ((FileSplit) split).getPath();
         filenameKey = new Text(path.toString());
      }
      @Override
      protected void map(NullWritable key, BytesWritable value,
            Context context) throws IOException, InterruptedException {
         context.write(filenameKey, value);
      }
   }
   @Override
   public int run(String[] args) throws Exception {
      Configuration conf = new Configuration();
      Job job = Job.getInstance(conf,"combine small files to sequencefile");
      job.setJarByClass(SmallFilesToSequenceFileConverter.class);
      job.setInputFormatClass(WholeFileInputFormat.class);
      WholeFileInputFormat.addInputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\5、大数据离线第五天\\自定义inputformat_小文件合并\\input"));
      job.setOutputFormatClass(SequenceFileOutputFormat.class);
      SequenceFileOutputFormat.setOutputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\5、大数据离线第五天\\自定义inputformat_小文件合并\\output"));
      job.setOutputKeyClass(Text.class);
      job.setOutputValueClass(BytesWritable.class);
      job.setMapperClass(SequenceFileMapper.class);
      return job.waitForCompletion(true) ? 0 : 1;
   }
   public static void main(String[] args) throws Exception {
      int exitCode = ToolRunner.run(new SmallFilesToSequenceFileConverter(),
            args);
      System.exit(exitCode);
      
   }
} 

9、自定义outputFormat

在这里插入图片描述

第一步:自定义一个outputformat

public class MyOutPutFormat extends FileOutputFormat<Text,NullWritable> {
    @Override
    public RecordWriter<Text, NullWritable> getRecordWriter(TaskAttemptContext context) throws IOException, InterruptedException {
        FileSystem fs = FileSystem.get(context.getConfiguration());
        Path enhancePath = new Path("file:///F:\\传智播客大数据离线阶段课程资料\\5、大数据离线第五天\\自定义outputformat\\out1\\1.txt");
        Path toCrawlPath = new Path("file:///F:\\传智播客大数据离线阶段课程资料\\5、大数据离线第五天\\自定义outputformat\\out2\\2.txt");
        FSDataOutputStream enhanceOut = fs.create(enhancePath);
        FSDataOutputStream toCrawlOut = fs.create(toCrawlPath);
        return new MyRecordWriter(enhanceOut,toCrawlOut);
    }
    static class MyRecordWriter extends RecordWriter<Text, NullWritable>{

        FSDataOutputStream enhanceOut = null;
        FSDataOutputStream toCrawlOut = null;

        public MyRecordWriter(FSDataOutputStream enhanceOut, FSDataOutputStream toCrawlOut) {
            this.enhanceOut = enhanceOut;
            this.toCrawlOut = toCrawlOut;
        }

        @Override
        public void write(Text key, NullWritable value) throws IOException, InterruptedException {
            if (key.toString().split("\t")[9].equals("0")){
                toCrawlOut.write(key.toString().getBytes());
                toCrawlOut.write("\r\n".getBytes());
            }else{
                enhanceOut.write(key.toString().getBytes());
                enhanceOut.write("\r\n".getBytes());
            }
        }
        @Override
        public void close(TaskAttemptContext context) throws IOException, InterruptedException {
            if(toCrawlOut!=null){
                toCrawlOut.close();
            }
            if(enhanceOut!=null){
                enhanceOut.close();
            }
        }
    }
}

第二步:开发mapreduce处理流程

public class MyOwnOutputFormatMain extends Configured implements Tool {
    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = super.getConf();
        Job job = Job.getInstance(conf, MyOwnOutputFormatMain.class.getSimpleName());
        job.setJarByClass(MyOwnOutputFormatMain.class);
        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat.addInputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\5、大数据离线第五天\\自定义outputformat\\input"));
        job.setMapperClass(MyOwnMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);
        job.setOutputFormatClass(MyOutPutFormat.class);
        //设置一个输出目录,这个目录会输出一个success的成功标志的文件
        MyOutPutFormat.setOutputPath(job,new Path("file:///F:\\传智播客大数据离线阶段课程资料\\5、大数据离线第五天\\自定义outputformat\\out2"));
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);
        boolean b = job.waitForCompletion(true);
        return b?0:1;
    }
        public static class MyOwnMapper extends Mapper<LongWritable,Text,Text,NullWritable>{
            @Override
            protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
                String[] split = value.toString().split("\t");
                String commentStatus = split[9];
               context.write(value,NullWritable.get());
            }
        }
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        ToolRunner.run(configuration,new MyOwnOutputFormatMain(),args);
    }
}

2、Mapreduce的其他补充

1 多job串联

一个稍复杂点的处理逻辑往往需要多个mapreduce程序串联处理,多job的串联可以借助mapreduce框架的JobControl实现

在这里插入图片描述
在这里插入图片描述
5.3 Configuration对象高级应用

3、mapreduce参数优化

**1 资源相关参数**

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值