之前熟悉的流处理API中的转换算子是无法访问事件的时间戳信息和水位线信息的。例如:MapFunction这样的map转换算子就无法访问时间戳或者当前事件的时间。然而,在一些场景下,又需要访问这些信息。基于此,DataStream API提供了一系列的Low-Level转换算子。这些算子支持访问时间戳、watermark以及注册定时事件。还可以输出特定的一些事件,例如超时事件等。Process Function用来构建事件驱动的应用以及实现自定义的业务逻辑(使用之前的window函数和转换算子无法实现)。例如:Flink SQL就是使用Process Function实现的。
Flink提供了8个Process Function:
①ProcessFunction
②KeyedProcessFunction
③CoProcessFunction
④ProcessJoinFunction
⑤BroadcastProcessFunction
⑥KeyedBroadcastProcessFunction
⑦ProcessWindowFunction
⑧ProcessAllWindowFunction
1 KeyedProcessFunction
由于KeyedStream是最常用的,而KeyedProcessFunction又用来操作KeyedStream,所以这里重点介绍KeyedProcessFunction。KeyedProcessFunction会处理流的每一个元素,输出为0个,1个或者多个元素。所有的Process Function都继承自RichFunction接口,所以都有open()、close()和getRuntimeContext()等方法。而KeyedProcessFunction[KEY,IN,OUT]还提供了另外两个方法:
①processElement(value:IN,ctx:Context,out:Collector[OUT]),流中的每一个元素都会调用这个方法,调用结果将会放在Collector数据类型中输出。Context可以访问元素的时间戳,元素的key,以及TimeService时间服务。Context还可以将结果输出到别的流(side outputs)。
②onTimer(timestamp:Long,ctx:OntimerContext,out:Collector[OUT])是一个回调函数。
当之前注册的定时器触发时调用。参数timestamp位定时器所设定的触发的时间戳。Collector为输出结果的集合。OnTimerContext和processElement的Context参数一样,提供了上下文的一些信息,例如定时器触发的时间信息(事件时间或者处理时间)。
2 TimerService和定时器(Timer)
Context和OnTimeContext所持有的TimerService对象拥有以下方法:
①currentProcessingTime():Long返回当前处理时间
②currentWatermark():Long返回当前watermark的时间戳
③registerProcessingTimeTimer(timestamp:Long):Unit注册当前key的processing time
的定时器。当processing time到达定时时间时,触发timer。
④registerEventTimeTimer(timestamp:Long):Unit注册当前key的event time定时器。
当水位线大于等于定时器注册的时间时,触发定时器执行回调函数。
⑤deleteProcessingTimeTime(timestamp:Long): Unit删除之前注册处理时间定时器。
如果没有这个时间戳的定时器,则不执行。
⑥deleteEventTimeTimer(timestamp:Long): Unit删除之前注册的event time定时器,如果没有此时间戳的定时器,则不执行。
当定时器timer触发时,会执行回调函数onTimer()。注意定时器只能在KeyedStream上使用。
接下来举一个例子说明KeyedProcessFunction如何操作KeyedStream。
需求1:监控温度传感器的温度值,如果温度值在10秒之内(process time)连续上升,则报警。
object ProcessFunctionTest {
def main(args: Array[String]): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
env.setParallelism(1)
val inputStream = env.socketTextStream(IP地址,7777)
val dataStream = inputStream.map(
data =>{
val dataArr = data.split(",")
SensorReading(dataArr(0).trim,dataArr(1).trim.toLong,dataArr(2).trim.toDouble)
}
)
.assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor[SensorReading](Time.milliseconds(1000)) {
override def extractTimestamp(element: SensorReading): Long = {
element.timeStamp * 1000L
}
})
val processStream = dataStream.keyBy(_.id)
.process(new TempIncreAlert())
dataStream.print("dataStream")
processStream.print("processStream")
env.execute("process function test")
}
}
class TempIncreAlert() extends KeyedProcessFunction[String,SensorReading,String]{
// 定义一个状态,用来保存上一个数据的温度值
lazy val lastTemp:ValueState[Double] = getRuntimeContext.getState(new ValueStateDescriptor[Double](