通过对HDFS的了解,接下来我们接着来学习hadoop第二个核心MapReduce。
一.概述
*MapReduce是一个分布式计算模型,是用户开发“基于hadoop的数据分析应用”的核心框架。将用户编写的业务逻辑代码和自带默认组件整合成一个完整的分布式运算程序,并发运行在一个hadoop集群上。
*主要用于搜索领域、处理海量数据的计算问题。
*由Map和Reduce两个阶段组成,用户只需实现Map和Reduce函数,即可实现分布式计算,两个函数的形参是key、value对,表示函数输入信息。
二.优缺点
1.优点:
*易于编程。实现一些接口,就可以完成一个分布式程序;
*良好的扩展性。
*高容错性。能够部署在廉价的pc机器上,比如一台机器挂掉,它可以把计算任务转移到另外节点上运行,不至于运行失败。
*适合PB级以上海量数据的离线处理.。
2.缺点:
*不擅长实时计算。无法像mysql一样,在毫秒或秒级返回结果;
*不擅长流式计算。流式计算的数据杀死动态的,而mapreduce的输入数据集是静态,不能动态变化;
*不擅长DAG有向图计算。多个应用程序存在依赖关系,后一个应用程序的输入前一个的输出。每个mapreduce输出结果写入磁盘会导致磁盘IO,影响性能。
三.三类实例进程
一个完整的MapReduce程序在分布式运行时有三类实例进程:
*MrAppMaster:负责整个程序的过程调度及状态协调;
*MapTask:负责map阶段整个数据处理流程;
*ReduceTask:负责reduce阶段整个数据处理流程。
四.简单案例
统计以文本中每个单词出现的总次数,下面是该文本内容(例:ss 2)
shenghuo shenghuo
ss ss
cls cls
jiao
banzhang
xue
hadoop
*首先创建一个maven工程,在pom.xml文件中添加如下依赖:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>3.1.3</version>
</dependency>
</dependencies>
*在项目的src/main/resources目录下新建文件log4j2.xml并写入内容:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="error" strict="true" name="XMLConfig">
<Appenders>
<!-- 类型名为Console,名称为必须属性 -->
<Appender type="Console" name="STDOUT">
<!-- 布局为PatternLayout的方式,
输出样式为[INFO] [2018-01-22 17:34:01][org.test.Console]I'm here -->
<Layout type="PatternLayout"
pattern="[%p] [%d{yyyy-MM-dd HH:mm:ss}][%c{10}]%m%n" />
</Appender>
</Appenders>
<Loggers>
<!-- 可加性为false -->
<Logger name="test" level="info" additivity="false">
<AppenderRef ref="STDOUT" />
</Logger>
<!-- root loggerConfig设置 -->
<Root level="info">
<AppenderRef ref="STDOUT" />
</Root>
</Loggers>
</Configuration>
*编写Mapper类:
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 WcMapper 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().split(" ");
//输出
for (String ros : line){
//封装对象
k.set(ros);
context.write(k,v);
}
}
}
*编写Reduce类:
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class WcReduce extends Reducer<Text, IntWritable,Text,IntWritable> {
int sum ;
IntWritable v = new IntWritable();
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
//累加求和
sum = 0;
for (IntWritable count : values){
sum += count.get();
}
//输出
v.set(sum);
context.write(key,v);
}
}
*编写Driver驱动类:
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.output.FileOutputFormat;
import java.io.IOException;
public class WcDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
args = new String[]{"src/main/java/file/wc.txt","src/main/java/cn/text_01/result"};
//获取配置和joo对象实例
Configuration config = new Configuration();
Job job = Job.getInstance(config);
//设置jar加载路径
job.setJarByClass(WcDriver.class);
//设置map和reduce类
job.setMapperClass(WcMapper.class);
job.setReducerClass(WcReduce.class);
//设置map输出
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
//合并,减少网络传输,指定需要使用Combiner,以及用哪个类作为Combiner的逻辑
//job.setCombinerClass(WcReduce.class);
//设置最终输出
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.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);
}
}
*运行完结果如下:
banzhang 1
shenghuo 2
cls 2
hadoop 1
jiao 1
ss 2
xue 1
五.Shuffle机制(Map方法之后,Reduce方法之前的数据处理过程)
1.Partition分区:
*概述:Mapper任务划分数据的过程称作分区。负责实现划分数据的类称为Partitioner。例:进行MapReduce计算时,不同性别的信息放到不同的文件中。partition是分割map每个节点的结果,按照key分别映射给不同的reduce,也是可以自定义的。
*使用方法:定义一个类并继承Partitioner,实现里面的getPartition()方法。在驱动类中设置自定义分区和ReduceTasks数量,此数量一定要和分区数保持一致。
*案例(将统计结果按照手机归属地不同省份输出到不同文件中):
1).文件内容
1 13736230513 192.196.100.1 www.shenghuo.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.shenghuo.com 1527 2106 200
6 84188413 192.168.100.3 www.shenghuo.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.shenghuo.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
2).编写mapper类
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import java.io.IOException;
public class Mapper extends org.apache.hadoop.mapreduce.Mapper<LongWritable, Text,Text, Bean> {
Text k = new Text();
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
//获取行内容并以空格分割
String[] line = value.toString().split("\t");
//获取手机号、上行流量、下行流量
String phone = line[1];
long upFlow = Long.parseLong(line[line.length - 3]);
long downFlow = Long.parseLong(line[line.length - 2]);
//输出
k.set(phone);
Bean v = new Bean(upFlow,downFlow);
context.write(k,v);
}
}
3).编写reduce类
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class Reduce extends Reducer<Text, Bean,Text,Bean> {
@Override
protected void reduce(Text key, Iterable<Bean> values, Context context) throws IOException, InterruptedException {
//定义总的上行流量和下行流量,把相同手机号的信息相加
long sum_upFlow = 0;
long sum_downFlow = 0;
for (Bean line : values) {
sum_upFlow += line.getUpFlow();
sum_downFlow += line.getDownFlow();
}
//输出
Bean v = new Bean(sum_upFlow,sum_downFlow);
context.write(key,v);
}
}
4).Bean类
import org.apache.hadoop.io.Writable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public class Bean implements Writable {
private long upFlow; //上行流量
private long downFlow; //下行流量
private long sumFlow; //总流量
public Bean() {
super();
}
public Bean(long upFlow, long downFlow) {
this.upFlow = upFlow;
this.downFlow = downFlow;
this.sumFlow = upFlow + downFlow;
}
public long getUpFlow() {
return upFlow;
}
public void setUpFlow(long upFlow) {
this.upFlow = upFlow;
}
public long getDownFlow() {
return downFlow;
}
public void setDownFlow(long downFlow) {
this.downFlow = downFlow;
}
public long getSumFlow() {
return sumFlow;
}
public void setSumFlow(long sumFlow) {
this.sumFlow = sumFlow;
}
@Override
public String toString() {
return upFlow + "\t" + downFlow + "\t" + sumFlow;
}
//序列化
@Override
public void write(DataOutput out) throws IOException {
out.writeLong(upFlow);
out.writeLong(downFlow);
out.writeLong(sumFlow);
}
//反序列化
@Override
public void readFields(DataInput in) throws IOException {
this.upFlow = in.readLong();
this.downFlow = in.readLong();
this.sumFlow = in.readLong();
}
}
5).Partitioner分区类
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Partitioner;
public class BPartitioner extends Partitioner<Text,Bean> {
@Override
public int getPartition(Text key, Bean value, int i) {
//获取电话号码的前三位
String phone = key.toString().substring(0, 3);
//设置分区数
int partition = 5;
//判断
if ("136".equals(phone)){
partition = 0;
}else if ("137".equals(phone)){
partition = 1;
}else if ("138".equals(phone)){
partition = 2;
}else if ("139".equals(phone)){
partition = 3;
}else {
partition = 4;
}
return partition;
}
}
6).驱动类
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 Driver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
args = new String[]{"src/main/java/file/phone.txt","src/main/java/cn/text_02/result"};
//获取配置和joo对象实例
Configuration config = new Configuration();
Job job = Job.getInstance(config);
//设置jar加载路径
job.setJarByClass(Driver.class);
//设置map和reduce类
job.setMapperClass(Mapper.class);
job.setReducerClass(Reduce.class);
//设置map输出
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Bean.class);
//设置自定义分区
job.setPartitionerClass(BPartitioner.class);
//设置reduce任务数
job.setNumReduceTasks(5);
//设置最终输出
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Bean.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);
}
}
2.WritableComparable排序(默认为正序排序,字典排序法)
*概述:按照key进行排序,属于hadoop默认行为,任何应用程序中的数据均会被排序,而不是逻辑上的需要。
*分类:
1).部分排序:mapreduce根据输入记录的键对数据集排序,保证输出的每个文件内部有序。
2).全排序:最终输出结果只有一个文件,且文件内部有序。
3).二次排序:在自定义排序过程中,如果compareto中的判断条件为两个即为二次排序。
*案例:
在分区案例的基础上对总流量进行降序排序如下(修改Bean类即可,Bean类实现WritableComparable接口重写compartTo方法,并把bean作为key传输)
import org.apache.hadoop.io.WritableComparable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public class PaiXuBean implements WritableComparable<PaiXuBean> {
private long upFlow; //上行流量
private long downFlow; //下行流量
private long sumFlow; //总流量
public PaiXuBean() {
super();
}
public PaiXuBean(long upFlow, long downFlow) {
this.upFlow = upFlow;
this.downFlow = downFlow;
this.sumFlow = upFlow + downFlow;
}
public long getUpFlow() {
return upFlow;
}
public void setUpFlow(long upFlow) {
this.upFlow = upFlow;
}
public long getDownFlow() {
return downFlow;
}
public void setDownFlow(long downFlow) {
this.downFlow = downFlow;
}
public long getSumFlow() {
return sumFlow;
}
public void setSumFlow(long sumFlow) {
this.sumFlow = sumFlow;
}
@Override
public String toString() {
return upFlow + "\t" + downFlow + "\t" + sumFlow;
}
//序列化
@Override
public void write(DataOutput out) throws IOException {
out.writeLong(upFlow);
out.writeLong(downFlow);
out.writeLong(sumFlow);
}
//反序列化
@Override
public void readFields(DataInput in) throws IOException {
this.upFlow = in.readLong();
this.downFlow = in.readLong();
this.sumFlow = in.readLong();
}
//对总流量降序
@Override
public int compareTo(PaiXuBean bean) {
int result;
if (this.sumFlow > bean.getSumFlow()){
result = -1;
}else if (this.sumFlow < bean.getSumFlow()){
result = 1;
}else {
result = 0;
}
return result;
}
}
3.Combiner合并
*概述:是MapReduce程序中Mapper和Reduce之外的一种组件,它的父类就是Reduce。应用的前提是不能影响最终的业务逻辑。
在map端对输出先做一次合并,以减少传输到reducer的数据量,提升效率。
的输出是Reducer的输入,Combiner绝不能改变最终的计算结果。所以 Combiner只应该用于那种Reduce的输入key/value与输出key/value类型完全一 致,且不影响最终结果的场景。比如累加,最大值等,求平均值不适用。
*使用方法:自定义一个Combiner类并继承Reduce,重写Reduce方法,在驱动类里面添加合并类(job.setCombinerClass(Combiner.class))。