Flink中的ProcessFunction API(温度报警案例)

ProcessFunction API:
DataStream API 提供了一系列的 Low-Level 转换算子。可以访问时间戳、watermark 以及注册定时事件。还可以输出特定的一些事件,例如超时事件等。Process Function 用来构建事件驱动的应用以及实现自定义的业务逻辑(使用之前的window 函数和转换算子无法实现)。例如,Flink SQL 就是使用 Process Function 实现的。
KeyedProcessFunction:
KeyedProcessFunction 用来操作 KeyedStream。KeyedProcessFunction 会处理流的每一个元素,输出为 0 个、1 个或者多个元素。所有的 Process Function 都继承自RichFunction 接口,所以都有 open()、close()和 getRuntimeContext()等方法。而KeyedProcessFunction[KEY, IN, OUT]还额外提供了两个方法: 
processElement(v: IN, ctx: Context, out: Collector[OUT]), 流中的每一个元素都会调用这个方法,调用结果将会放在 Collector 数据类型中输出。Context可以访问元素的时间戳,元素的 key,以及 TimerService 时间服务。Context还可以将结果输出到别的流(side outputs)。
onTimer(timestamp: Long, ctx: OnTimerContext, out: Collector[OUT])是一个回调函数。当之前注册的定时器触发时调用。参数 timestamp 为定时器所设定的触发的时间戳。Collector 为输出结果的集合。OnTimerContext 和processElement 的 Context 参数一样,提供了上下文的一些信息,例如定时器触发的时间信息(事件时间或者处理时间)。
温度报警案例:

package flink.chapter5WaterMark

import org.apache.flink.api.common.state.ValueStateDescriptor
import org.apache.flink.api.scala.typeutils.Types
import org.apache.flink.streaming.api.functions.KeyedProcessFunction
import org.apache.flink.util.Collector
import org.apache.flink.api.scala._
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.scala.{DataStream, KeyedStream, StreamExecutionEnvironment}
class PorceTempFunc extends KeyedProcessFunction[String,(String,Long,Double),String]{
  //获取上一次温度值为历史温度
  lazy val lastTemp = getRuntimeContext.getState(new ValueStateDescriptor[Double]("lastTemp",Types.of[Double]))
  //获取定时器时间
  lazy val curTimer = getRuntimeContext.getState(new ValueStateDescriptor[Long]("curTimer",Types.of[Long]))
  override def processElement(value: (String, Long, Double), ctx: KeyedProcessFunction[String, (String, Long, Double), String]#Context, out: Collector[String]): Unit = {
    //获取历史温度的值
    val perTemp: Double = lastTemp.value()
    //将新传入的元素当中的温度更新到历史温度中,成为新的历史温度
    lastTemp.update(value._3)
    //获取定时器时间戳
    val curTimeStamp: Long = curTimer.value()
    //进行判断,看看温度是上升还是下降
    if(value._3<perTemp||perTemp==0){
      //传进来的温度如果下降或是之前就没有过历史温度,当前传入为第一次温度,就要删除定时器信息
      ctx.timerService().deleteProcessingTimeTimer(curTimer.value())
      curTimer.clear()
    }else if(value._3>perTemp&& curTimeStamp==0){
      //我要延迟1s去报警
      val TimeTs: Long = ctx.timerService().currentProcessingTime()+5000L
      //我要注册定时器
      ctx.timerService().registerProcessingTimeTimer(TimeTs)
      //将时间更新成定时器时间
      curTimer.update(TimeTs)
    }
  }

  //如果温度连续上升,就要调用回调函数OnTimer方法进行报警
  override def onTimer(timestamp: Long, ctx: KeyedProcessFunction[String, (String, Long, Double), String]#OnTimerContext, out: Collector[String]): Unit = {
    //既然要输出结果,就要收集结果
    out.collect("当前传感器id为:"+ctx.getCurrentKey+"已经连续1s温度上升")
    //清空定时器信息
    curTimer.clear()
  }
}
object enter{
  //main方法
  def main(args: Array[String]): Unit = {
    //构建flink流处理的执行环境
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
    //设置并行度
    env.setParallelism(1)
    //设置使用时间类型
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
    //接收数据
    val data: DataStream[String] = env.socketTextStream("hadoop101",9999)
    //针对传入的数据进行操作
    val file: DataStream[(String, Long, Double)] = data.map(text => {
      val arr: Array[String] = text.split("\t")
      (arr(0), arr(1).toLong, arr(2).toDouble)
    })
    //分流
    val keyed: KeyedStream[(String, Long, Double), String] = file.keyBy(_._1)
    //针对传入的数据进行操作
    val window: DataStream[String] = keyed.process(new PorceTempFunc)
    //打印输出
    file.print("keyed:")
    //传入的数据进行打印
    window.print("window::")
    //调用execute方法
    env.execute()
  }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值