Spark Streaming自定义Receivers

本文介绍如何自定义一个接收器类来实现Spark流处理应用,包括类的实现、Actor作为接收器的使用及合并多个输入流的方法。通过Netcat测试验证了自定义接收器的功能。

自定义一个Receiver

 class SocketTextStreamReceiver(host: String, port: Int(
         extends NetworkReceiver[String]
       {
         protected lazy val blocksGenerator: BlockGenerator =
           new BlockGenerator(StorageLevel.MEMORY_ONLY_SER_2)

         protected def onStart() = {
           blocksGenerator.start()
           val socket = new Socket(host, port)
           val dataInputStream = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"))
           var data: String = dataInputStream.readLine()
           while (data != null) {
             blocksGenerator += data
             data = dataInputStream.readLine()
           }
         }

         protected def onStop() {
           blocksGenerator.stop()
         }
       }

An Actor as Receiver

 class SocketTextStreamReceiver (host:String,
         port:Int,
         bytesToString: ByteString => String) extends Actor with Receiver {

          override def preStart = IOManager(context.system).connect(host, port)

          def receive = {
           case IO.Read(socket, bytes) => pushBlock(bytesToString(bytes))
         }

       }

A Sample Spark Application

  val ssc = new StreamingContext(master, "WordCountCustomStreamSource",
      Seconds(batchDuration))
//使用自定义的receiver val lines
= ssc.networkStream[String](new SocketTextStreamReceiver( "localhost", 8445))

//或者使用这个自定义的actor Receiver val lines2
= ssc.actorStream[String](Props(new SocketTextStreamReceiver( "localhost",8445, z => z.utf8String)),"SocketReceiver") */
    val words = lines.flatMap(_.split(" "))
    val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _)
    wordCounts.print()
    ssc.start()

提交成功之后,启动Netcat测试一下

$ nc -l localhost 8445 hello world hello hello

下面是合并多个输入流的方法:

  val lines = ssc.actorStream[String](Props(new SocketTextStreamReceiver(
      "localhost",8445, z => z.utf8String)),"SocketReceiver")

  // Another socket stream receiver
  val lines2 = ssc.actorStream[String](Props(new SocketTextStreamReceiver(
      "localhost",8446, z => z.utf8String)),"SocketReceiver")

  val union = lines.union(lines2)

 

 

转载于:https://www.cnblogs.com/cenyuhai/p/3577583.html

### 创建使用自定义 Receiver 的过程 为了在 Spark Streaming 应用程序中创建并使用自定义接收器,需遵循特定的方法来构建 `CustomReceiver` 类,并将其集成到流处理框架内。 #### 定义自定义接收器类 首先,需要继承 `Receiver` 抽象类,并重写其方法以实现具体的功能逻辑。下面是一个简单的例子: ```scala import org.apache.spark.streaming.receiver.Receiver import java.net.{ServerSocket, Socket} class CustomReceiver(host: String, port: Int) extends Receiver[String](StorageLevel.MEMORY_AND_DISK_2) { def onStart() { // 启动线程执行 receive 方法 new Thread("Socket Receiver") { override def run() { receive() } }.start() } def onStop() { // 停止接收数据的操作 } /** Create a socket connection and receive data until receiver is stopped */ private def receive() { var socket: Socket = null try { // 连接到服务器套接字 val serverSocket = new ServerSocket(port) LogInfo(s"Connecting to $host:$port") socket = serverSocket.accept() LogInfo(s"Connected to $host:$port") // 将收到的数据发送给存储引擎 val input = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)) var line: String = "" while (!isStopped && (line = input.readLine()) != null) { store(line) } LogInfo("Stopped receiving") onStop() } catch { case e: Throwable => restart(s"Error connecting or reading from socket", e) } finally { if (socket != null) socket.close() } } } ``` 这段代码展示了如何建立一个基于 TCP 协议的自定义接收器[^1]。 #### 配置 StreamingContext 启动应用 一旦有了自定义接收器之后,在主函数里配置好 `StreamingContext` 并调用 `receiverStream()` 来注册这个新的接收器实例即可开始工作流程。 ```scala val conf = new SparkConf().setMaster("local[*]").setAppName("CustomReceiverApp") // 设置日志级别为 ERROR 减少控制台输出干扰 conf.set("spark.logConf","false").set("spark.driver.bindAddress","localhost") val ssc = new StreamingContext(conf, Seconds(1)) // 使用自定义接收器获取实时数据流 val customReceiverStream = ssc.receiverStream(new CustomReceiver("localhost", 9999)) // 对接收到的数据做进一步操作比如单词计数等... customReceiverStream.flatMap(_.split(" ")) .map((_, 1)) .reduceByKey(_ + _) .print() ssc.start() // 开始接受数据 ssc.awaitTermination() // 等待终止信号 ``` 此部分实现了通过 `StreamingContext` 初始化以及利用之前定义好的 `CustomReceiver` 获取来自指定主机与端口的数据流,并进行了基本的文字分割平铺映射转换成键值对形式以便后续聚合计算。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值