Flink雙流處理:實時對賬實現

更多內容詳見:https://github.com/pierre94/flink-notes

一、基礎概念

主要是兩種處理模式:

  • Connect/Join
  • Union

二、雙流處理的方法

Connect

DataStream,DataStream → ConnectedStreams

連接兩個保持他們類型的數據流,兩個數據流被Connect之後,只是被放在了一個同一個流中,內部依然保持各自的數據和形式不發生任何變化,兩個流相互獨立。

Connect後使用CoProcessFunction、CoMap、CoFlatMap、KeyedCoProcessFunction等API 對兩個流分別處理。如CoMap:

val warning = high.map( sensorData => (sensorData.id, sensorData.temperature) )
val connected = warning.connect(low)

val coMap = connected.map(
warningData => (warningData._1, warningData._2, "warning"),
lowData => (lowData.id, "healthy")
)

(ConnectedStreams → DataStream 功能與 map 一樣,對 ConnectedStreams 中的每一個流分別進行 map 和 flatMap 處理。)

疑問,既然兩個流內部獨立,那Connect 後有什麼意義呢?

Connect後的兩條流可以共享狀態,在對賬等場景具有重大意義!

Union


DataStream → DataStream:對兩個或者兩個以上的 DataStream 進行 union 操作,產生一個包含所有 DataStream 元素的新 DataStream。

val unionStream: DataStream[StartUpLog] = appStoreStream.union(otherStream) unionStream.print("union:::")

注意:Union 可以操作多個流,而Connect只能對兩個流操作

Join

Join是基於Connect更高層的一個實現,結合Window實現。

相關知識點比較多,詳細文檔見: https://ci.apache.org/projects/flink/flink-docs-release-1.10/dev/stream/operators/joining.html

三、實戰:實時對賬實現

需求描述

有兩個時間Event1、Event2,第一個字段是時間id,第二個字段是時間戳,需要對兩者進行實時對賬。當其中一個事件缺失、延遲時要告警出來。

需求分析

類似之前的訂單超時告警需求。之前數據源是一個流,我們在function裏面進行一些改寫。這裏我們分別使用Event1和Event2兩個流進行Connect處理。

// 事件1
case class Event1(id: Long, eventTime: Long)
// 事件2
case class Event2(id: Long, eventTime: Long)
// 輸出結果
case class Result(id: Long, warnings: String)

代碼實現

scala實現

涉及知識點:

  • 雙流Connect
  • 使用OutputTag側輸出
  • KeyedCoProcessFunction(processElement1、processElement2)使用
  • ValueState使用
  • 定時器onTimer使用

啓動兩個TCP服務:

nc -lh 9999
nc -lk 9998

注意:nc啓動的是服務端、flink啓動的是客戶端

import java.text.SimpleDateFormat

import org.apache.flink.api.common.state.{ValueState, ValueStateDescriptor}
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.functions.co.KeyedCoProcessFunction
import org.apache.flink.streaming.api.scala.{StreamExecutionEnvironment, _}
import org.apache.flink.util.Collector

object CoTest {
  val simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy:HH:mm:ss")
  val txErrorOutputTag = new OutputTag[Result]("txErrorOutputTag")


  def main(args: Array[String]): Unit = {
    val env = StreamExecutionEnvironment.getExecutionEnvironment
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
    env.setParallelism(1)

    val event1Stream = env.socketTextStream("127.0.0.1", 9999)
      .map(data => {
        val dataArray = data.split(",")
        Event1(dataArray(0).trim.toLong, simpleDateFormat.parse(dataArray(1).trim).getTime)
      }).assignAscendingTimestamps(_.eventTime * 1000L)
      .keyBy(_.id)

    val event2Stream = env.socketTextStream("127.0.0.1", 9998)
      .map(data => {
        val dataArray = data.split(",")
        Event2(dataArray(0).trim.toLong, simpleDateFormat.parse(dataArray(1).trim).getTime)
      }).assignAscendingTimestamps(_.eventTime * 1000L)
      .keyBy(_.id)

    val coStream = event1Stream.connect(event2Stream)
      .process(new CoTestProcess())

    //    union 必須是同一條類型的流
    //    val unionStream = event1Stream.union(event2Stream)
    //    unionStream.print()

    coStream.print("ok")
    coStream.getSideOutput(txErrorOutputTag).print("txError")

    env.execute("union test")
  }

  //共享狀態
  class CoTestProcess() extends KeyedCoProcessFunction[Long,Event1, Event2, Result] {
    lazy val event1State: ValueState[Boolean]
    = getRuntimeContext.getState(new ValueStateDescriptor[Boolean]("event1-state", classOf[Boolean]))

    lazy val event2State: ValueState[Boolean]
    = getRuntimeContext.getState(new ValueStateDescriptor[Boolean]("event2-state", classOf[Boolean]))


    override def processElement1(value: Event1, ctx: KeyedCoProcessFunction[Long, Event1, Event2, Result]#Context, out: Collector[Result]): Unit = {
      if (event2State.value()) {
        event2State.clear()
        out.collect(Result(value.id, "ok"))
      } else {
        event1State.update(true)
        //等待一分鐘
        ctx.timerService().registerEventTimeTimer(value.eventTime + 1000L * 60)
      }
    }

    override def processElement2(value: Event2, ctx: KeyedCoProcessFunction[Long, Event1, Event2, Result]#Context, out: Collector[Result]): Unit = {
      if (event1State.value()) {
        event1State.clear()
        out.collect(Result(value.id, "ok"))
      } else {
        event2State.update(true)
        ctx.timerService().registerEventTimeTimer(value.eventTime + 1000L * 60)
      }
    }

    override def onTimer(timestamp: Long, ctx: KeyedCoProcessFunction[Long, Event1, Event2, Result]#OnTimerContext, out: Collector[Result]): Unit = {
      if(event1State.value()){
        ctx.output(txErrorOutputTag,Result(ctx.getCurrentKey,s"no event2,timestamp:$timestamp"))
        event1State.clear()
      }else if(event2State.value()){
        ctx.output(txErrorOutputTag,Result(ctx.getCurrentKey,s"no event1,timestamp:$timestamp"))
        event2State.clear()
      }
    }
  }

}

相關閱讀

《Flink狀態編程: 訂單超時告警》:
https://blog.csdn.net/u013128262/article/details/104648592

《github:Flink學習筆記》:
https://github.com/pierre94/flink-notes


原創聲明,本文系作者授權雲+社區發表,未經許可,不得轉載。

https://cloud.tencent.com/developer/article/1596145

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章