一. Hadoop 序列化概念

1. 序列化概述

  1. 什么是序列化
    序列化就是把内存中的对象, 转换成字节序列(或其他数据传输协议)以便于存储到磁盘(持久化)和网络传输
    反序列化就是将收到的字节序列(其他数据传输协议)或是磁盘的持久化数据, 转换成内存中的对象
  2. 为什么要序列化
    一般来说,“活的“对象只生存在内存里,关机断电就没有了。而且“活的"对象只能由本地的进程使用,不能被发送到网络上的另外一台计算机。然而序列化可以存储“活的”对象,可以将“活的”对象发送到远程计算机。
  3. 为什么不用java的序列化
    Java]序列化是一个重量级序列化框架(Serializable),一个对象被序列化后,会附带很多额外的信息(各种校验信息,Header,继承体系等),不便于在网络中高效传输。所以,Hadoop自己开发了一套序列化机制(Writable)。
  4. Hadoop序列化特点:
  • 紧凑:高效使用存储空间。
  • 快速:读写数据的额外开销小。
  • 可扩展:随着通信协议的升级而可升级
  • 互操作:支持多语言的交互

2. 自定义bean对象实现序列化接口(Writable)

在Hadoop框架内部传递一个bean对象,那么该对象就需要实现序列化接口。

  1. 必须实现Writable接口
  2. 反序列化时, 需要反射调用空参构造函数, 所以必须有空参构造
public FlowBean() {
	super();
}
  1. 重写序列化方法
@Override
public void write(DataOutput out) throws IOException {
	out.writeLong(upFlow);
	out.writeLong(downFlow);
	out.writeLong(sumFlow);
}
  1. 重写反序列化方法
@Override
public void readFields(DataInput in) throws IOException {
	upFlow = in.readLong();
	downFlow = in.readLong();
	sumFlow = in.readLong();
}
  1. 注意反序列化的顺序和序列化的顺序必须保持完全一致
  2. 要想把结果显示在文件中,需要重写toString()
  3. 如果需要将自定义的bean放在key中传输,则还需要实现Comparable接口,因为MapReduce框中的Shuffle过程要求对key必须能排序。
@Override
public int compareTo(FlowBean o) {
	// 倒序排列,从大到小
	return this.sumFlow > o.getSumFlow() ? -1 : 1;
}

二. Hadoop序列化的应用

1. 题目

  1. 问题: 统计每一个手机号耗费的总上行流量、下行流量、总流量
  2. 数据集:
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 	15784188413	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
  1. 输出格式:
13560436666 	1116			954 		2070
手机号码		    上行流量      	下行流量		总流量

2. 代码

  1. Driver 端
package com.hjf.mr.phoneData;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
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;

/**
 * @author Jiang锋时刻
 * @create 2020-05-17 17:53
 */
public class PhoneDataDriver {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);

        job.setJarByClass(PhoneDataDriver.class);

        job.setMapperClass(PhoneDataMapper.class);
        job.setReducerClass(PhoneDataReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(DataFlow.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(DataFlow.class);

        Path inputPath = new Path("./Data/phone_data.txt");
        Path outputPath = new Path("./Data/result");

        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(outputPath)) {
            fs.delete(outputPath, true);
        }

        FileInputFormat.setInputPaths(job, inputPath);
        FileOutputFormat.setOutputPath(job, outputPath);

        job.waitForCompletion(true);
    }
}
  1. Mapper 端
package com.hjf.mr.phoneData;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/**
 * @author Jiang锋时刻
 * @create 2020-05-17 17:55
 */
public class PhoneDataMapper extends Mapper<LongWritable, Text, Text, DataFlow> {
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String[] lines = value.toString().split("\t");
        int len = lines.length;
        Text phone = new Text(lines[1]);
        int upFlow = Integer.parseInt(lines[len - 3]);
        int downFlow = Integer.parseInt(lines[len - 2]);

        DataFlow dataFlow = new DataFlow(upFlow, downFlow);
        context.write(phone, dataFlow);

    }
}
  1. Reducer 端
package com.hjf.mr.phoneData;

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

import java.io.IOException;

/**
 * @author Jiang锋时刻
 * @create 2020-05-17 17:55
 */
public class PhoneDataReducer extends Reducer<Text, DataFlow, Text, DataFlow> {

    @Override
    protected void reduce(Text key, Iterable<DataFlow> values, Context context) throws IOException, InterruptedException {
        int upFlow = 0;
        int downFlow = 0;
        for (DataFlow value: values) {
            upFlow += value.getUpFlow();
            downFlow += value.getDownFlow();
        }
        DataFlow result = new DataFlow(upFlow, downFlow);
        context.write(key, result);
    }
}
  1. DataFlow 类(自定义类)
package com.hjf.mr.phoneData;

import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;

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

/**
 * @author Jiang锋时刻
 * @create 2020-05-17 19:05
 */
// 1. 实现Writable接口 
public class DataFlow implements Writable {
    private long upFlow;
    private long downFlow;
    private long sumFlow;
	
	// 2. 发序列化时, 需要反射调用空参构造器, 所以必须要有
    public DataFlow() {
    }

    public DataFlow(long upFlow, long downFlow) {
        this.upFlow = upFlow;
        this.downFlow = downFlow;
        this.sumFlow = upFlow + downFlow;
    }

    public long getUpFlow() {
        return upFlow;
    }

    public long getDownFlow() {
        return downFlow;
    }

    public long getSumFlow() {
        return sumFlow;
    }

	// 3. 序列化方法
    @Override
    public void write(DataOutput out) throws IOException {
        out.writeLong(upFlow);
        out.writeLong(downFlow);
        out.writeLong(sumFlow);
    }
	
	// 4. 反序列化方法
	// 5. 反序列化方法读顺序必须和序列化方法的写顺序保持一致
    @Override
    public void readFields(DataInput in) throws IOException {
        upFlow = in.readLong();
        downFlow = in.readLong();
        sumFlow = in.readLong();
    }
	
	// 编写toString方法, 方便后续打印
    @Override
    public String toString() {
        return "upFlow=" + upFlow +
                "\tdownFlow=" + downFlow +
                "\tsumFlow=" + sumFlow;
    }
}