如何实现自定义接收器来接收特定数据源的数据
解读
在国内一线互联网公司(如阿里、腾讯、字节)的实时数仓或风控场景中,经常需要把自研消息中间件、私有协议网关或 IoT 设备日志接入 Spark Streaming。官方内置的 Kafka、Flume、MQTT 接收器往往无法满足“私有协议 + 一次语义 + 背压控制”的严苛要求,因此“手写一个 Custom Receiver”是面试里区分“API 调用者”与“内核掌控者”的高频考点。面试官不仅想看你能不能继承 Receiver[T] 或实现 Source/Sink V2,更关注你对“容错、背压、零数据丢失、内存保护、调优”是否有体系化思考。
知识点
- Spark Streaming 时代:Receiver + WAL + BlockGenerator 的容错模型;onStart/onStop/stopGracefully 生命周期;store(data) 与 push-based 背压。
- Structured Streaming 时代:Source V2 接口(MicroBatchStream、ContinuousStream)、Offset、OffsetLog、CommitLog、StreamingDataSourceV2;与 Spark 3.x 的 Adaptive Query Execution 协同。
- 端到端一致性:幂等写、幂等接收、WAL 双写、Kafka 事务、Checkpoints idempotent restore。
- 性能与稳定:背压(spark.streaming.backpressure.enabled)、Receiver 并行度(numPartitions)、BlockInterval 调优、内存安全(maxRatePerPartition、backpressure.pid)。
- 国内合规:数据分类分级、脱敏、审计日志、跨城容灾(两地三中心)对接自定义接收器时的埋点与拦截。
答案
以 Structured Streaming 为例,给面试官一个“能直接落地”的源码级思路(Scala 2.12,Spark 3.4)。
步骤 1:定义私有协议数据样例类
case class DeviceLog(deviceId: String, ts: Long, payload: Array[Byte])
步骤 2:实现 MicroBatchStream
class DeviceTcpMicroBatchStream(options: CaseInsensitiveStringMap)
extends MicroBatchStream with Logging {
private val host = options.get("host")
private val port = options.getInt("port", 8866)
private val maxRate = options.getInt("maxRatePerPartition", 10000)
// 用 ConcurrentLinkedQueue 缓存背压水位
private val queue = new java.util.concurrent.ConcurrentLinkedQueueDeviceLog
@volatile private var client: TcpClient = _
@volatile private var running = false
override def planInputPartitions(start: Offset, end: Offset): Array[InputPartition] = {
val startOffset = DeviceTcpOffset(start.json().toLong)
val endOffset = DeviceTcpOffset(end.json().toLong)
val range = endOffset.offset - startOffset.offset
val numPartitions = Math.min(range, 64).toInt
Array.tabulate(numPartitions)(i => DeviceTcpPartition(i, numPartitions, startOffset, endOffset))
}
override def createReaderFactory: PartitionReaderFactory =
(partition: InputPartition) => new DeviceTcpPartitionReader(partition.asInstanceOf[DeviceTcpPartition], queue)
override def initialOffset(): Offset = DeviceTcpOffset(0L)
override def latestOffset(): Offset = DeviceTcpOffset(System.currentTimeMillis())
override def deserializeOffset(json: String): Offset = DeviceTcpOffset(json.toLong)
override def commit(end: Offset): Unit = { /* 可写外部 offset 存储 */ }
override def stop(): Unit = {
running = false
if (client != null) client.close()
}
// 启动私有协议长连接
private def startReceiver(): Unit = {
running = true
client = new TcpClient(host, port)
client.connect()
while (running) {
val log = client.read()
if (queue.size() < maxRate) queue.offer(log)
else Thread.sleep(50) // 简单背压
}
}
// 在 Driver 启动后台线程
new Thread("device-tcp-receiver") { override def run(): Unit = startReceiver() }.start()
}
步骤 3:注册 DataSource
class DeviceTcpSource extends DataSourceRegister with TableProvider {
override def shortName(): String = "deviceTcp"
override def getTable(...) = new DeviceTcpTable(...)
}
步骤 4:使用
val df = spark.readStream
.format("deviceTcp")
.option("host", "10.0.0.101")
.option("port", 8866)
.option("maxRatePerPartition", 8000)
.load()
df.writeStream
.format("delta")
.option("checkpointLocation", "/hdfs/dw/checkpoint/device")
.outputMode("append")
.start()
容错要点
- Offset 以毫秒时间戳表示,单调递增,重启时从 Checkpoint 恢复。
- 每条 DeviceLog 带唯一 uuid,下游 Delta 表按 uuid 主键去重,实现幂等。
- 网络断线时 client 内部指数退避重连,重连成功继续追加 queue,不抛异常。
- 背压通过 queue.size() 与 maxRate 比较,防止 Driver OOM。
拓展思考
- 如果私有协议要求“仅一次”且不能改源码,可把接收器做成 Kafka Connect 插件,先写 Kafka,再用 Spark 消费,利用 Kafka 事务保证端到端仅一次。
- 对于百万级 IoT 并发,考虑 Netty + Epoll 替代阻塞 IO,并在 Receiver 端做批量攒包(micro batching),降低每事件开销。
- 国内等保 2.0 要求传输加密,需在 TcpClient 里集成国密 SM4 或 TLS 双向证书,并在 commit 阶段写审计日志到 Hive 审计表。
- Spark 3.5 的 Thread-Stage 调度模型对 Continuous Processing 更友好,可评估把 MicroBatchStream 升级为 ContinuousStream,实现毫秒级低延迟。