flink求连续下滑

1.设置使用哪个来指定时间

如果使用的是秒 记得转换成毫秒 *1000

2.写状态

3.获取值和状态 (进行比较 设置下降状态)

4.设置定时器和删除定时器

定时器的代码查找

 

 修改分数

 最后输出  ontime

 数据

001,math,10,1646038440

001,math,12,1646038441

001,math,11,1646038442

001,math,10,1646038443

001,math,9,1646038444

001,math,8,1646038445

001,math,7,1646038446

001,math,6,1646038447

001,math,7,1646038448

001,math,4,1646038449

代码

/**
 * @author jiasongfan
 * @date 2022/5/31
 * @apiNote
 */
import org.apache.flink.api.common.state.{ValueState, ValueStateDescriptor}
import org.apache.flink.streaming.api.functions.{KeyedProcessFunction, ProcessFunction}
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.util.Collector
object Test04 {
  def main(args: Array[String]): Unit = {
    val env = StreamExecutionEnvironment.getExecutionEnvironment
    env.setParallelism(1)
    val text = env.socketTextStream("hdp1", 9999)
    val mapDS: DataStream[StuScore] = text.map(line => {
      val li: Array[String] = line.split(",")
      StuScore(li(0), li(1), li(2).trim.toInt,li(3).trim.toLong*1000)
    })
    //设置下滑的时间格式
    val timeDS: DataStream[StuScore] = mapDS.assignAscendingTimestamps(_.ts)


    val keyS: KeyedStream[StuScore, String] = timeDS.keyBy(_.id)
    keyS.process(new MyPro2).print()
    env.execute()
  }
}
//<K, I, O>
class MyPro2 extends KeyedProcessFunction[String,StuScore,String]{
  //上一次的数据
  lazy val state: ValueState[Int] = getRuntimeContext
    .getState(new ValueStateDescriptor[Int]("myState", classOf[Int]))
  //上升或下降状态   也可以呃是string   我这里使用 1  和 -1
  lazy val flag: ValueState[Int] = getRuntimeContext
    .getState(new ValueStateDescriptor[Int]("flag", classOf[Int]))
  //定时器  类型 long
  lazy val timer: ValueState[Long] = getRuntimeContext
    .getState(new ValueStateDescriptor[Long]("timer", classOf[Long]))


  override def processElement(i: StuScore, context: KeyedProcessFunction[String, StuScore, String]#Context, collector: Collector[String]): Unit = {
      //获取值和状态
      val v: Int = state.value()
    val f: Int = flag.value()

    //判断是否是第一次下降
    if(i.score<v){
      //设置定时器
      if(f==1){
        context.timerService.registerEventTimeTimer(i.ts + 5000)
      }


      //记录
      flag.update(-1)

    }else{
      //取消定时器
      context.timerService.deleteProcessingTimeTimer(timer.value())
      flag.update(1)
    }
    state.update(i.score)
  }

  override def onTimer(timestamp: Long, ctx: KeyedProcessFunction[String, StuScore, String]#OnTimerContext, out: Collector[String]): Unit = {
    out.collect("连续下滑")
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值