[flink] ProcessFunction应用示例

[flink] ProcessFunction应用示例


需求:对于DataStream[SensorReading]数据流,若某个sensor的温度在10秒之内连续上升则报警


/** 需求: 对于DataStream[SensorReading]数据流,若某个sensor的温度在10秒之内连续上升则报警
  * 分析: 保存两个状态,上一条数据的温度值(用来和本条数据比较),之前开始统计的定时器的时间戳
  */

class TempIncreWarning(interval: Long) extends KeyedProcessFunction[String, SensorReading, String]{
	// 定义状态,保存上一个温度值进行比较,保存注册定时器的时间戳用于删除定时器
	lazy val lastTempState: ValueState[Double] = getRuntimeContext.getState(new ValueStateDescriptor[Double]("last-temp", classOf[Double]))
	lazy val timerTsState: ValueState[Long] = getRuntimeContext.getState(new ValueStateDescriptor[Long]("timer-ts", classOf[Long]))

	// KeyedProcessFunction的K,I,O泛型为ID(String),SensorReading,String(报警信息)
	override def processElement(value: SensorReading, ctx: KeyedProcessFunction[String, SensorReading, String]#Context, out: Collector[String]): Unit = {
		// 先取出保存的状态
		val lastTemp = lastTempState.value
		val timerTs = timerTsState.value
		lastTempState.update(value.temperature)

		// 当前温度值和上次温度值比较
		if (value.temperature > lastTemp && timerTs == 0){
			// 如果温度上升,且没有定时器,就注册当前时间10s之后的定时器
			val ts = ctx.timerService().currentProcessingTime() + interval
			ctx.timerService.registerProcessingTimeTimer(ts)
			timerTsState.update(ts)
		} else if (value.temperature < lastTemp){
			// 若温度下降,删除定时器
			ctx.timerService.deleteProcessingTimeTimer(timerTs)
			timerTsState.clear()
		}
	}

	override def onTimer(timestamp: Long, ctx: KeyedProcessFunction[String, SensorReading, String]#OnTimer, out: Collector[String]): Unit = {
		// 若能触发定时器,说明10s之内肯定没被删除,意味着这10s内的数据符合报警条件,直接输出就完事
		// 利用out进行输出
		out.collect("传感器" + ctx.getCurrentKey + "的温度连续" + interval/1000 + "秒连续上升")
		// 清空定时器
		timerTsState.clear()
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值