序列化avro schema

// 将schema转换为字节数组

val schemaBytes: Array[Byte] = schema.toString.getBytes(StandardCharsets.UTF_8)

// 将字节数组包装为可序列化的对象

val serializableSchemaBytes: SerializableBytes = new SerializableBytes(schemaBytes)

// 将字节数组反序列化为schema对象

val schemaString = new String(serializableSchemaBytes.bytes, StandardCharsets.UTF_8)

val schema = new Schema.Parser().parse(schemaString)

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream, Serializable}

class SerializableBytes(val bytes: Array[Byte]) extends Serializable {

  private def writeObject(out: ObjectOutputStream): Unit = {

    out.writeInt(bytes.length)

    out.write(bytes)

  }

  private def readObject(in: ObjectInputStream): Unit = {

    val length = in.readInt()

    val buffer = new Array[Byte](length)

    in.readFully(buffer)

    bytes = buffer

  }

  def getInputStream: ByteArrayInputStream = new ByteArrayInputStream(bytes)

  def getOutputStream: ByteArrayOutputStream = new ByteArrayOutputStream(bytes.length)

}

需要将SerializableBytes类定义在Spark应用程序的可访问范围内,例如定义在主类或者全局对象中。另外,由于Schema对象在executor端反序列化时会重新创建,因此需要确保Schema类的定义也在executor端的类路径下。

NotSerializableException: org.apache.avro.Schema$RecordSchema

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值