在电商商品购买过程中有这样一些场景:用户点击下单,此时订单处于待支付状态,如果在2小时之后还处于待支付状态那么就将这笔订单取消,置为取消状态;用户收货之后可以对商品进行评价,如果在24小时内仍然没有评价,那么自动将用户对商品的评分设置为5星….等等,这样的场景都可以称之为延时处理场景,当数据发送出去了,不立刻进行处理,而是等待一段时间之后在处理,目前对于延时处理的方案也有很多,例如:
在流处理中也经常会有一些定时触发的场景,例如定时监控报警等,并且时间窗口的触发也是通过延时调用触发,接下来了解flink中是如何实现延时处理。
在flink实时处理中,涉及到延时处理可使用KeyedProcessFunction来完成,KeyedProcessFunction是flink提供面向用户的low level api,可以访问状态、当前的watermark或者当前的processingtime, 更重要的是提供了注册定时器的功能,分为:
看一个实际案例:服务器下线监控报警,服务器上下线都会发送一条消息,如果发送的是下线消息,在之后的5min内没有收到上线消息则循环发出警告,直到上线取消告警。 实现思路: 1.由于根据服务器不在线时间来告警,应该使用ProcessingTime语义 2.首先将服务器信息按照serverId分组,然后使用一个继承KeyedProcessFunction的类的Function接受处理,定义两个ValueState分别存储触发时间与服务器信息,
case class ServerMsg(serverId: String, isOnline: Boolean, timestamp: Long)
class MonitorKeyedProcessFunction extends KeyedProcessFunction[String, ServerMsg, String] {
private var timeState: ValueState[Long] = _
private var serverState: ValueState[String] = _
override def open(parameters: Configuration): Unit = {
timeState = getRuntimeContext.getState(new ValueStateDescriptor[Long]("time-state", TypeInformation.of(classOf[Long])))
serverState = getRuntimeContext.getState(new ValueStateDescriptor[String]("server-state", TypeInformation.of(classOf[String])))
}
override def processElement(value: ServerMsg, ctx: KeyedProcessFunction[String, ServerMsg, String]#Context, out: Collector[String]): Unit = {
if (!value.isOnline) {
val monitorTime = ctx.timerService().currentProcessingTime() + 300000
timeState.update(monitorTime)
serverState.update(value.serverId)
ctx.timerService().registerProcessingTimeTimer(monitorTime)
}
if (value.isOnline && -1 != timeState.value()) {
ctx.timerService().deleteProcessingTimeTimer(timeState.value())
timeState.update(-1)
}
}
override def onTimer(timestamp: Long, ctx: KeyedProcessFunction[String, ServerMsg, String]#OnTimerContext, out: Collector[String]): Unit = {
if (timestamp == timeState.value()) {
val newMonitorTime = timestamp + 300000
timeState.update(newMonitorTime)
ctx.timerService().registerProcessingTimeTimer(newMonitorTime)
println("告警:" + serverState.value() + " is offline, please restart")
}
}
}
注意点:只能在KeyedStream中注册定时器。
上图表示flink延时调用的总体流程,其设计也是借助于优先级队列来完成,队列中存储的数据结构如下:
end