十一 迟到数据的处理

1 可以更新窗口已经计算完的结果,并发出计算结果

DataStream API 提供了三种策略来处理迟到元素:
• 直接抛弃迟到的元素(event time window operator 的默认行为)
• 将迟到的元素发送到另一条流中去
(https://blog.csdn.net/andyonlines/article/details/108067446)
• 可以更新窗口已经计算完的结果,并发出计算结果(我们现在要讲的)

我们可以指定一个时间段叫做 allowed lateness。 window operator 如果设置了 allowed lateness,这个 window operator 在水位线没过窗口结束时间时也将不会删除窗口和窗口中的状态。窗口会在一段时间内 (allowed lateness 设置的) 保留所有的元素。当迟到元素在 allowed lateness 时间内到达时,这个迟到元素会被实时处理并发送到触发器(trigger)。当水位线没过了窗口结束时间 +allowed lateness 时间时,窗口会被删除,并且所有后来的迟到的元素都会被丢弃。

2 案例:

package org.example.join


import org.apache.flink.api.common.state.ValueStateDescriptor
import org.apache.flink.api.scala.typeutils.Types
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.time.Time
import org.example.source.self.{SensorReading, SensorSource}
import org.apache.flink.streaming.api.scala.function.ProcessWindowFunction
import org.apache.flink.streaming.api.windowing.windows.TimeWindow
import org.apache.flink.util.Collector

object AllowedLatenessExample {
  def main(args: Array[String]): Unit = {
    val env = StreamExecutionEnvironment.getExecutionEnvironment
    env.setParallelism(1)
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
    val reading = env.addSource(new SensorSource).assignAscendingTimestamps(_.timestamp)

    val countStream = reading.keyBy(_.id)
      .timeWindow(Time.seconds(10)) //开窗
      .allowedLateness(Time.seconds(5)) //窗口延时5秒更新数据
      /**
       * 如果真的有用迟到数据,每个窗口触发两次process
       * 一次是水位线超过窗口大小
       * 第二次是水位线超过allowedLateness
       */
      .process(new UpdatingWindowCountFunction)
      .print()

    env.execute()
  }


  class UpdatingWindowCountFunction extends ProcessWindowFunction[SensorReading,(String, Long, Int, String), String, TimeWindow] {
    override def process(key: String, context: Context, elements: Iterable[SensorReading], out: Collector[(String, Long, Int, String)]): Unit = {
      val cnt = elements.count(_ => true)

      /**
       * 状态变量是用来记录是都否是水位线超过allowedLateness引发的process
       */
      val isUpdate = context.windowState.getState(
        new ValueStateDescriptor[Boolean](
          "isUpdate",
          Types.of[Boolean]
        )
      )


      if (!isUpdate.value()) {
        out.collect((key,context.window.getEnd,cnt, "frist")) //是水位线超过allowedLateness引发的process
        isUpdate.update(true)
      } else {
        out.collect( (key,context.window.getEnd,cnt,"update"))//不是是水位线超过allowedLateness引发的process
      }

    }
  }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值