0. 序列化介绍

  1. 序列化
  • 内存中的Java对象—> 硬盘/网络
  1. 反序列化
  • 把硬盘/网络中的对象—->内存

序列化技术

  1. Serializable 接口 序列化出来的文件太大, 不利于文件的网络传输
  2. JSON 把对象转换为一个json字符串 {“name”:”tom”,”age:18,”sex”:”M”}
  3. Writable Hadoop内置序列化方式 —DataInputStream DataOutPutStream
  • 读写的顺序必须一致
  1. Avro/Protobuf(java/C)

    1. 对象的序列化

    我们都知道,当我们需要把一个 Java 对象从内存中保存到磁盘中或者从内存中的对象通过网络传输到另外 一个地方的,我们都必须把对象进行序列化操作
    在我们的 Spark 程序中,会有很多对象都需要进行网络通 信,比如说我们需要把我们在 Driver 端生成的 Task 任务发送到 Executor 中去执行任务,那么我们需要先对 这个 Task 任务进行序列化才能在网络上传输,但是很多时候我们在写 Spark 程序的时候,会保存对象没有 序列化操作,所以我们先来彻底的了解一下序列化的操作

    1.1. Java 对象的序列化

    实现序列化接口的对象

    1. public class Student implements Serializable {
    2. private Long id;
    3. private String name;
    4. private Integer age;
    5. public Student() {}
    6. public Student(Long id, String name, Integer age) {
    7. this.id = id;
    8. this.name = name;
    9. this.ag = age;
    10. }
    11. }

    将一个java对象序列化后写入磁盘中
    然后再将磁盘的对象序列化文件读取,生成一个对象

    1. //java 的对象序列化
    2. public class JavaSerDemo {
    3. //序列化到磁盘
    4. @Test
    5. public void testwrite() throws Exception {
    6. //1 创建一个对象
    7. Student s1 = new Student(1L, "hesj", 18);
    8. //day06.cn.wolfcode.spark.ser.Student@ba4d54
    9. System.out.println("序列化之前的对象:"+s1);
    10. //2 把对象保存到磁盘
    11. FileOutputStream fos = new FileOutputStream("d:/s1.dat");
    12. ObjectOutputStream oos = new ObjectOutputStream(fos);
    13. oos.writeObject(s1);
    14. //关闭流对象,同时会关闭 fos
    15. oos.close();
    16. }
    17. //从磁盘读取文件
    18. @Test
    19. public void testRead() throws Exception {
    20. FileInputStream fis = new FileInputStream("d:/s1.dat");
    21. ObjectInputStream ois = new ObjectInputStream(fis);
    22. Student s1 = (Student) ois.readObject();
    23. //day06.cn.wolfcode.spark.ser.Student@c818063
    24. System.out.println("反序列化的一个对象:"+s1);
    25. ois.close();
    26. FileInputStream fis2 = new FileInputStream("d:/s1.dat");
    27. ObjectInputStream ois2 = new ObjectInputStream(fis2);
    28. Student s2 = (Student) ois2.readObject();
    29. //day06.cn.wolfcode.spark.ser.Student@c818032
    30. System.out.println("反序列化的一个对象:"+s2);
    31. ois.close();
    32. }
    33. }

    通过上面这个程序, 我们可以看出来

  • 实现序列化操作需要实现 Serializable
  • 反序列化创建的一个文件和我们序列化出去的一个对象不再是同一个对象

    1.2. 理解 Spark 中的序列化

    方式一

  • 定义一个映射规则对象

  • 因为规则映射是在 Executor 中使用的,所以在每个 Executor 中都创建一个规则映射对象
  • 也即:如果有 10 个executor,则会创建10个规则映射对象 ```scala class Rules { //定义一个映射的规则 val rulesMap = Map(“hadoop” -> 2.7, “spark” -> 2.2,”java”->1.8) //获取到当前创建改 Rules 对象的一个主机名 val hostname = InetAddress.getLocalHost.getHostName //打印主机名 println(hostname + “@@@@@@@@@@@@@@@@”) }

object SerTest { def main(args: Array[String]): Unit = { val conf = new SparkConf().setAppName(“SerTest”) val sc = new SparkContext(conf) val lines: RDD[String] = sc.textFile(args(0)) val r = lines.map(word => { val rules = new Rules //获取当前的主机名称 val hostname = InetAddress.getLocalHost.getHostName //获取当前运行的线程名字 val threadName = Thread.currentThread().getName //rules 的实际是在 Executor 中使用的 (hostname, threadName, rules.rulesMap.getOrElse(word, 0), rules.toString) }) r.saveAsTextFile(args(1)) sc.stop() } }

  1. 通过日志我们发现两个问题:
  2. - 对于我们的具体的任务执行,创建规则对象是在 Executor 端创建的
  3. - 对于不同的线程中所创建的任务规则也是不一样的, 所以我们需要一个 Rules 对象都会创建再立即销
  4. <a name="fnTqI"></a>
  5. ### 方式二
  6. - 对于方式一,显示是不合理的
  7. - 使用 scala 的**闭包**特性,在匿名函数内,可以使用函数外面的变量
  8. - 此时就避免了广播的操作
  9. - 但注意:存在网络传输,还是需要序列化的
  10. - 我们可以在 Driver 中只创建一次,然后后面在各个 Executor 中一直引用同一个对
  11. 象即可
  12. ```scala
  13. class Rules extends Serializable # 类需要实现序列化
  14. object SerTest {
  15. def main(args: Array[String]): Unit = {
  16. val conf = new SparkConf().setAppName("SerTest")
  17. val sc = new SparkContext(conf)
  18. val lines: RDD[String] = sc.textFile(args(0))
  19. //在 Driver 端创建我们的规则
  20. val rules = new Rules
  21. val r = lines.map(word => {
  22. //获取当前的主机名称
  23. val hostname = InetAddress.getLocalHost.getHostName
  24. //获取当前运行的线程名字
  25. val threadName = Thread.currentThread().getName
  26. //rules 的实际是在 Executor 中使用的
  27. (hostname, threadName, rules.rulesMap.getOrElse(word, 0), rules.toString)
  28. })
  29. //当我们在执行调度我们的任务的时候, task 会序列化我们的 Rule 规则
  30. r.saveAsTextFile(args(1))
  31. sc.stop()
  32. }
  33. }

方式三

  • 使用广播的方式(对象也需要序列化)
  • 每个 Executor 有一份,不是每个 Task 一份 ```scala object SerTest { def main(args: Array[String]): Unit = { val conf = new SparkConf().setAppName(“SerTest”) val sc = new SparkContext(conf) val lines: RDD[String] = sc.textFile(args(0)) //在 Driver 端创建我们的规则 val rules = new Rules val rulesRef: Broadcast[Rules] = sc.broadcast(rules) val r = lines.map(word => {
    1. val currentRule: Rules = rulesRef.value
    2. //获取当前的主机名称
    3. val hostname = InetAddress.getLocalHost.getHostName
    4. //获取当前运行的线程名字
    5. val threadName = Thread.currentThread().getName
    6. //rules 的实际是在 Executor 中使用的
    7. (hostname, threadName, currentRule.rulesMap.getOrElse(word, 0), currentRule.toString)
    }) //当我们在执行调度我们的任务的时候, task 会序列化我们的 Rule 规则 r.saveAsTextFile(args(1)) sc.stop() } }
  1. 方式四
  2. - 使用一个单例对象
  3. ,然后各个 Executor 使用同一个对象
  4. ```scala
  5. object Rules {
  6. //定义一个映射的规则
  7. val rulesMap = Map("hadoop" -> 2.7, "spark" -> 2.2,"java"->1.8)
  8. //获取到当前创建改 Rules 对象的一个主机名
  9. val hostname = InetAddress.getLocalHost.getHostName
  10. //打印主机名
  11. println(hostname + "@@@@@@@@@@@@@@@@")
  12. }

2. Spark 中的并发

并发问题出现地方

  • 被抽出去的公共静态类的成员属性

并发问题原因

  • 公共静态类会被多个线程同时调用执行,此时成员属性就面临并发问题

这里我们通过一个简单的并发的实例来了解一下

  1. object GameKPI {
  2. def main(args: Array[String]): Unit = {
  3. //"2016-02-01"
  4. val startDate = args(0)
  5. //"2016-02-02"
  6. val endDate = args(1)
  7. //查询条件
  8. val dateFormat1 = new SimpleDateFormat("yyyy-MM-dd")
  9. //查寻条件的的起始时间
  10. val startTime = dateFormat1.parse(startDate).getTime
  11. //查寻条件的的截止时间
  12. val endTime = dateFormat1.parse(endDate).getTime
  13. //Driver 定义的一个 simpledataformat
  14. val dateFormat2 = new SimpleDateFormat("yyyy 年 MM 月 dd 日,E,HH:mm:ss")
  15. val conf = new SparkConf().setAppName("GameKPI").setMaster("local[2]")
  16. val sc = new SparkContext(conf)
  17. //从哪里读取数据
  18. val lines: RDD[String] = sc.textFile(args(2))
  19. //整理并过滤
  20. val splited: RDD[Array[String]] = lines.map(line => line.split("[|]"))
  21. //按日期过过滤
  22. val filterd = splited.filter(fields => {
  23. val t = fields(0)
  24. val time = fields(1)
  25. val timeLong = dateFormat2.parse(time).getTime
  26. t.equals("1") && timeLong >= startTime && timeLong < endTime
  27. })
  28. val dnu = filterd.count()
  29. println(dnu)
  30. sc.stop()
  31. }
  32. }

上述程序可以正常访问资源
定义一个工具类, 简化代码和业务操作
并发问题:


  • ```java object FilterUtils{ //如果 object 使用了成员变量,那么会出现线程安全问题,因为 object 是一个单例,多线程可以同时调用这个方法 //val dateFormat = new SimpleDateFormat(“yyyy 年 MM 月 dd 日,E,HH:mm:ss”)

    //FastDateFormat 是线程安全的 val dateFormat = FastDateFormat.getInstance(“yyyy 年 MM 月 dd 日,E,HH:mm:ss”)

    def filterByType(fields: Array[String], tp: String) = {

    1. val _tp = fields(0)
    2. _tp == tp

    }

    def filterByTime(fields: Array[String], startTime: Long, endTime: Long) = {

    1. val time = fields(1)
    2. val timeLong = dateFormat.parse(time).getTime
    3. timeLong >= startTime && timeLong < endTime

    } }

object GameKPIV2 { def main(args: Array[String]): Unit = { //“2016-02-01” val startDate = args(0) //“2016-02-05” val endDate = args(1) val dateFormat1 = new SimpleDateFormat(“yyyy-MM-dd”) val startTime = dateFormat1.parse(startDate).getTime val endTime = dateFormat1.parse(endDate).getTime val conf = new SparkConf().setAppName(“GameKPIV2”).setMaster(“local[2]”) val sc = new SparkContext(conf) //以后从哪里读取数据 val lines: RDD[String] = sc.textFile(args(2)) //整理并过滤 val splited: RDD[Array[String]] = lines.map(line => line.split(“[|]”)) // 按日期过过滤 val filteredByType = splited.filter(fields => { FilterUtils.filterByType(fields, “1”) }) val filtered = filteredByType.filter(fields => { FilterUtils.filterByTime(fields, startTime, endTime) }) val dnu = filtered.count() println(dnu) sc.stop() } }

```