Shuffle机制与自定义分区

1、Shuffle机制

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

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

 

2、MapReduce的分区与reduceTask的数量 

        在MapReduce中,通过我们指定分区,会将同一个分区的数据发送到同一个reduce当中进行处理(默认是key相同去往同个分区),例如我们为了数据的统计,我们可以把一批类似的数据发送到同一个reduce当中去,在同一个reduce当中统计相同类型的数据,如何才能保证相同key的数据去往同个reduce呢?只需要保证相同key的数据分发到同个分区即可。结合以上原理分析我们知道MR程序shuffle机制默认就是这种规则!! 

(1)分区源码

翻阅源码验证以上规则,MR程序默认使用的HashPartitioner,保证了相同的key去往同个分区!!

(2) 自定义分区

        实际生产中需求变化多端,默认分区规则往往不能满足需求,需要结合业务逻辑来灵活控制分区规则以及分区数量!!

如何制定自己需要的分区规则?

具体步骤

  1. 自定义类继承Partitioner,重写getPartition()方法
  2. 在Driver驱动中,指定使用自定义Partitioner
  3. 在Driver驱动中,要根据自定义Partitioner的逻辑设置相应数量的ReduceTask数量。

需求:按照不同的appkey把记录输出到不同的分区中

原始日志格式

001     001577c3     kar_890809             120.196.100.99     1116         954                       200
日志id 设备id         appkey(合作硬件厂商)   网络ip         自有内容时长(秒) 第三方内容时长(秒)     网络状态码

输出结果

根据appkey把不同厂商的日志数据分别输出到不同的文件中

相关数据参见博文:序列化Writable接口_悠然予夏的博客-CSDN博客

需求分析:

  • 面对业务需求,结合mr的特点,来设计map输出的kv,以及reduce输出的kv数据。
  • 一个ReduceTask对应一个输出文件,因为在shuffle机制中每个reduceTask拉取的都是某一个分区的数据,一个分区对应一个输出文件。
  • 结合appkey的前缀相同的特点,同时不能使用默认分区规则,而是使用自定义分区器,只要appkey前缀相同则数据进入同个分区。

整体思路

Mapper:

  1. 读取一行文本,按照制表符切分
  2. 解析出appkey字段,其余数据封装为PartitionBean对象(实现序列化Writable接口)
  3. 设计map()输出的kv,key-->appkey(依靠该字段完成分区),PartitionBean对象作为Value输出

Partition:

  • 自定义分区器,实现按照appkey字段的前缀来区分所属分区

Reduce:

  • reduce()正常输出即可,无需进行聚合操作

Driver:

  1. 在原先设置job属性的同时增加设置使用自定义分区器
  2. 注意设置ReduceTask的数量(与分区数量保持一致)

代码示例 

Mapper

package com.lagou.mr.partition;

import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/**
 * 1. 读取一行文本,按照制表符切分
 * 2. 解析出appkey字段,其余数据封装为PartitionBean对象(实现序列化Writable接口)
 * 3. 设计map()输出的kv,key-->appkey(依靠该字段完成分区),PartitionBean对象作为Value输出
 */
public class PartitionMapper extends Mapper<LongWritable, Text, Text, PartitionBean> {
    PartitionBean bean = new PartitionBean();
    Text text = new Text();

    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, PartitionBean>.Context context) throws IOException, InterruptedException {
        final String[] fields = value.toString().split("\t");
        String appkey = fields[2];
        bean.setId(fields[0]);
        bean.setDeviceId(fields[1]);
        bean.setAppkey(appkey);
        bean.setIp(fields[3]);
        bean.setSelfDuration(Long.parseLong(fields[4]));
        bean.setThirdPartDuration(Long.parseLong(fields[5]));
        bean.setStatus(fields[6]);

        text.set(appkey);
        context.write(text, bean); // shuffle开始时会根据k的hashCode值进行分区,但是结合我们自己的业务,默认hash分区方式不能满足需求
    }
}

PartitionBean

package com.lagou.mr.partition;

import org.apache.hadoop.io.Writable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

public class PartitionBean implements Writable {
    // 定义属性
    private String id; // 日志id
    private String deviceId;// 设备id
    private String appkey;// appkey合作硬件厂商id
    private String ip;// ip地址
    private Long selfDuration;// 自有内容时长
    private Long thirdPartDuration;// 第三方内容时长
    private String status;// 状态码

    // 序列化
    @Override
    public void write(DataOutput out) throws IOException {
        out.writeUTF(id);
        out.writeUTF(deviceId);
        out.writeUTF(appkey);
        out.writeUTF(ip);
        out.writeLong(selfDuration);
        out.writeLong(thirdPartDuration);
        out.writeUTF(status);
    }

    // 反序列化, 要求序列化与反序列化字段顺序要保持一致
    @Override
    public void readFields(DataInput in) throws IOException {
        this.id = in.readUTF();
        this.deviceId = in.readUTF();
        this.appkey = in.readUTF();
        this.ip = in.readUTF();
        this.selfDuration = in.readLong();
        this.thirdPartDuration = in.readLong();
        this.status = in.readUTF();
    }

    // 空参构造
    public PartitionBean() {
    }

    // 有参构造
    public PartitionBean(String id, String deviceId, String appkey, String ip, Long selfDuration, Long thirdPartDuration, String status) {
        this.id = id;
        this.deviceId = deviceId;
        this.appkey = appkey;
        this.ip = ip;
        this.selfDuration = selfDuration;
        this.thirdPartDuration = thirdPartDuration;
        this.status = status;
    }

    public String getId() {
        return id;
    }

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

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }

    public String getAppkey() {
        return appkey;
    }

    public void setAppkey(String appkey) {
        this.appkey = appkey;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Long getSelfDuration() {
        return selfDuration;
    }

    public void setSelfDuration(Long selfDuration) {
        this.selfDuration = selfDuration;
    }

    public Long getThirdPartDuration() {
        return thirdPartDuration;
    }

    public void setThirdPartDuration(Long thirdPartDuration) {
        this.thirdPartDuration = thirdPartDuration;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return id + '\t' +
                deviceId + '\t' +
                appkey + '\t' +
                ip + '\t' +
                selfDuration + '\t' +
                thirdPartDuration +
                '\t' + status;
    }
}

CustomPartitioner

package com.lagou.mr.partition;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Partitioner;

// Partitioner分区器的泛型是map输出的kv类型
public class CustomPartitioner extends Partitioner<Text, PartitionBean> {
    @Override
    public int getPartition(Text text, PartitionBean partitionBean, int numPartitions) {
        int partition=0;
        if (text.toString().equals("kar")) {
            // 只需要保证满足此if条件的数据获得同个分区编号集合
            partition = 0;
        }else if (text.toString().equals("pandora")) {
            partition = 1;
        }else {
            partition = 2;
        }
        return partition;
    }
}

PartitionReducer

package com.lagou.mr.partition;


import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/* 输入类型:Text, PartitionBean
输出类型:Text, PartitionBean */
public class PartitionReducer extends Reducer<Text, PartitionBean, Text,PartitionBean> {
    @Override
    protected void reduce(Text key, Iterable<PartitionBean> values, Reducer<Text, PartitionBean, Text, PartitionBean>.Context context) throws IOException, InterruptedException {
        // 无需聚合运算,只需要进行输出即可
        for (PartitionBean value : values) {
            context.write(key, value);
        }
    }
}

PartitionDriver

package com.lagou.mr.partition;

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 PartitionDriver {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        // 获取配置文件
        Configuration conf = new Configuration();
        // 获取job实例
        Job job = Job.getInstance(conf);
        // 设置任务相关参数
        job.setJarByClass(PartitionDriver.class);
        job.setMapperClass(PartitionMapper.class);
        job.setReducerClass(PartitionReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(PartitionBean.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(PartitionBean.class);

        // 设置使用自定义分区器
        job.setPartitionerClass(CustomPartitioner.class);
        // 指定reduceTask数量与分区数量保持一致
        job.setNumReduceTasks(3); // reduceTask不设置默认是一个
        // 指定输入和输出路径
        FileInputFormat.setInputPaths(job, new Path("d:/Speak/speak.data"));
        FileOutputFormat.setOutputPath(job, new Path("d:/Speak/out"));

        final boolean flag = job.waitForCompletion(true);
        System.exit(flag ? 0 : 1);
    }
}

总结

  1. 自定义分区器时最好保证分区数量与reduceTask数量保持一致;
  2. 如果分区数量不止1个,但是reduceTask数量1个,此时只会输出一个文件。
  3. 如果reduceTask数量大于分区数量,但是输出多个空文件
  4. 如果reduceTask数量小于分区数量,有可能会报错。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悠然予夏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值