由于转换算子是无法访问事件的时间戳信息和水位线信息的。而这在一些应用场景下,极为重要。例如 MapFunction 这样的 map 转换算子就无法访问时间戳或者当前事件的事件时间。

基于此,DataStream API 提供了一系列的 Low-Level 转换算子。可以访问**时间戳**、**watermark** 以及**注册定时事件**。还可以输出**特定的一些事件**,例如超时事件等。Process Function 用来构建事件驱动的应用以及实现自定义的业务逻辑(使用之前的window 函数和转换算子无法实现)。例如,Flink SQL 就是使用 Process Function 实现的。

1. ProcessFunction的分类

Flink 提供了 8 个 Process Function:

  1. /**
  2. * ProcessFuntion
  3. * KeyedProcessFunction ------ keyBy之后的ProcessFunction
  4. * @author JShawn 2021/7/12 18:39
  5. */
  6. public class ProcessFunction_KeyedProcessFunction {
  7. public static void main(String[] args) throws Exception {
  8. StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
  9. // 可选,要想打印数据有序,可以设置并行度为1,默认是核心数
  10. env.setParallelism(1);
  11. // 1.Source:从socket读取数据
  12. DataStreamSource<String> inputDataStream = env.socketTextStream("localhost", 7777);
  13. // 2.可选,方法一(匿名对象):先转换成SensorReading
  14. DataStream<SensorReading> dataStream = inputDataStream.map(new MapFunction<String, SensorReading>() {
  15. @Override
  16. public SensorReading map(String value) throws Exception {
  17. String[] fields = value.split(",");
  18. return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
  19. }
  20. });
  21. // 3.******测试KeyedProcessFunction,先分组然后自定义处理******
  22. DataStream<SensorReading> resultStream = dataStream.keyBy("id")
  23. .process(new MyKeyedProcessFunction());
  24. // 4.打印
  25. resultStream.print();
  26. // 5.执行(jobName)
  27. env.execute("ProcessFunction_KeyedProcessFunction");
  28. }
  29. /**
  30. * 实现自定义的处理函数
  31. */
  32. public static class MyKeyedProcessFunction extends KeyedProcessFunction<Tuple, SensorReading, SensorReading> {
  33. private ValueState<Long> tsTimer;
  34. @Override
  35. public void open(Configuration parameters) throws Exception {
  36. tsTimer = getRuntimeContext().getState(new ValueStateDescriptor<Long>("ts-timer", Long.class));
  37. }
  38. // 处理数据
  39. @Override
  40. public void processElement(SensorReading sensorReading, Context context, Collector<SensorReading> collector) throws Exception {
  41. collector.collect(sensorReading);
  42. // Context
  43. context.timestamp(); //获取时间戳
  44. context.getCurrentKey(); //获取当前key
  45. // context.output(); //指定侧输出流
  46. // timerService
  47. // 定时器注册后,在生效时调用onTimer()
  48. context.timerService().currentProcessingTime(); //获取当前ProcessingTime
  49. context.timerService().currentWatermark(); //获取当前watermark,在这里就相当于eventTime
  50. context.timerService().registerEventTimeTimer((context.timestamp() + 10L) * 1000L); //注册timer,在绝对eventTime时间戳时注册定时器
  51. context.timerService().registerProcessingTimeTimer((context.timestamp() + 10000L) * 10); //注册timer,在绝对processingTime时间戳时注册定时器
  52. // 要删除的绝对时间戳,可以保存在状态State里
  53. tsTimer.update(context.timerService().currentProcessingTime() + 1000L);
  54. context.timerService().deleteEventTimeTimer(tsTimer.value()); // 删除绝对eventTime时间戳时的定时器
  55. context.timerService().deleteProcessingTimeTimer(tsTimer.value()); // 删除绝对processingTime时间戳时的定时器
  56. }
  57. /**
  58. * 定时器生效时调用onTimer()
  59. * @param timestamp 触发的时间戳
  60. * @param ctx 上下文
  61. * @param out 返回值收集器
  62. * @throws Exception
  63. */
  64. @Override
  65. public void onTimer(long timestamp, OnTimerContext ctx, Collector<SensorReading> out) throws Exception {
  66. // timestamp
  67. System.out.println(timestamp + "定时器触发");
  68. // OnTimerContext
  69. ctx.getCurrentKey();
  70. // ctx.output();
  71. ctx.timeDomain();
  72. }
  73. }
  74. }

3. TimerService 和 定时器(Timers)

Context 和 OnTimerContext 所持有的 TimerService 对象拥有以下方法:

  • long currentProcessingTime() 返回当前处理时间
  • long currentWatermark() 返回当前 watermark 的时间戳
  • void registerProcessingTimeTimer(long timestamp) 会注册当前 key 的processing time 的定时器。当 processing time 到达定时时间时,触发 timer。
  • void registerEventTimeTimer(long timestamp) 会注册当前 key 的 event time 定时器。当水位线大于等于定时器注册的时间时,触发定时器执行回调函数。
  • void deleteProcessingTimeTimer(long timestamp) 删除之前注册处理时间定时器。如果没有这个时间戳的定时器,则不执行。
  • void deleteEventTimeTimer(long timestamp) 删除之前注册的事件时间定时器,如果没有此时间戳的定时器,则不执行。

当定时器 timer 触发时,会执行回调函数 onTimer()。注意定时器 timer 只能在 keyedStream 上使用。

4. 综合案例

4.1 案例一(KeyedProcessFunction)

需求:监控温度传感器的温度值,如果温度值在 10 秒钟之内(processing time)连续上升,则报警。

  1. /**
  2. * ProcessFuntion
  3. * KeyedProcessFunction案例:监控温度传感器的温度值,如果温度值在 10 秒钟之内(processing time)连续上升,则报警。
  4. * @author JShawn 2021/7/12 18:39
  5. */
  6. public class ProcessFunction_KeyedProcessFunctionDemo {
  7. public static void main(String[] args) throws Exception {
  8. StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
  9. // 可选,要想打印数据有序,可以设置并行度为1,默认是核心数
  10. env.setParallelism(1);
  11. // 1.Source:从socket读取数据
  12. DataStreamSource<String> inputDataStream = env.socketTextStream("localhost", 7777);
  13. // 2.可选,方法一(匿名对象):先转换成SensorReading
  14. DataStream<SensorReading> dataStream = inputDataStream.map(new MapFunction<String, SensorReading>() {
  15. @Override
  16. public SensorReading map(String value) throws Exception {
  17. String[] fields = value.split(",");
  18. return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
  19. }
  20. });
  21. // 3.******测试KeyedProcessFunction,先分组然后自定义处理******
  22. dataStream.keyBy("id")
  23. .process(new TempConsIncreWarning(10))
  24. .print();
  25. // 5.执行(jobName)
  26. env.execute("ProcessFunction_KeyedProcessFunctionDemo");
  27. }
  28. /**
  29. * 实现自定义的处理函数,检测一段时间内的温度连续上升,输出报警
  30. */
  31. public static class TempConsIncreWarning extends KeyedProcessFunction<Tuple, SensorReading, String> {
  32. // 定义私有属性,当前统计的时间间隔
  33. private Integer interval;
  34. public TempConsIncreWarning(Integer interval) {
  35. this.interval = interval;
  36. }
  37. // 定义状态,保存上一次的温度值
  38. private ValueState<Double> lastTempState;
  39. // 定义状态,保存定时器时间戳
  40. private ValueState<Long> tsTimerState;
  41. @Override
  42. public void open(Configuration parameters) throws Exception {
  43. lastTempState = getRuntimeContext().getState(new ValueStateDescriptor<Double>("las-temp", Double.class, 0.0));
  44. tsTimerState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("ts-timer", Long.class));
  45. }
  46. // 处理数据
  47. @Override
  48. public void processElement(SensorReading sensorReading, Context context, Collector<String> collector) throws Exception {
  49. // 取出状态
  50. Double lastTemp = lastTempState.value();
  51. Long timerTs = tsTimerState.value();
  52. //如果温度上升,注册10秒后的定时器,开始等待
  53. if (sensorReading.getSensor() > lastTemp && null == timerTs) {
  54. // 计算出定时器时间戳
  55. Long ts = context.timerService().currentProcessingTime() + interval * 1000L;
  56. context.timerService().registerProcessingTimeTimer(ts);
  57. tsTimerState.update(ts);
  58. } else if (sensorReading.getSensor() < lastTemp && null != timerTs) {
  59. // 如果温度下降,那么删除定时器
  60. context.timerService().deleteProcessingTimeTimer(timerTs);
  61. tsTimerState.clear();
  62. }
  63. // 更新温度状态
  64. lastTempState.update(sensorReading.getSensor());
  65. }
  66. /**
  67. * 定时器触发时调用onTimer()
  68. * @param timestamp 触发的时间戳
  69. * @param ctx 上下文
  70. * @param out 返回值收集器
  71. * @throws Exception
  72. */
  73. @Override
  74. public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
  75. // 定时器触发,输出报警信息
  76. out.collect("传感器" + ctx.getCurrentKey().getField(0) + "温度值连续" + interval + "s上升");
  77. // 定时器出发后清空tsTimerState
  78. tsTimerState.clear();
  79. }
  80. // 结束时清空lastTempState
  81. @Override
  82. public void close() throws Exception {
  83. lastTempState.clear();
  84. }
  85. }
  86. }

4.2 案例二(ProcessFunction)

大部分的 DataStream API 的算子的输出是单一输出,也就是某种数据类型的流。除了 split 算子,可以将一条流分成多条流,这些流的数据类型也都相同。process function 的 side outputs 功能可以产生多条流,并且这些流的数据类型可以不一样。一个 side output 可以定义为 OutputTag对象,T 是输出流的数据类型。process function 可以通过 Context 对象发射一个事件到一个或者多个 side outputs。

需求:监控传感器温度值,温度值高于 30 度的高温流正常输出,将温度值低于 30 度的数据输出到 side output。

  1. /**
  2. * ProcessFuntion
  3. * ProcessFuntion:监控温度传感器的温度值,如果温度值在 30 度以上输出为高温流,低于 30 度输出为低温流
  4. * @author JShawn 2021/7/12 18:39
  5. */
  6. public class ProcessFunction_SideOutPutDemo {
  7. public static void main(String[] args) throws Exception {
  8. StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
  9. // 可选,要想打印数据有序,可以设置并行度为1,默认是核心数
  10. env.setParallelism(1);
  11. // 1.Source:从socket读取数据
  12. DataStreamSource<String> inputDataStream = env.socketTextStream("localhost", 7777);
  13. // 2.可选,方法一(匿名对象):先转换成SensorReading
  14. DataStream<SensorReading> dataStream = inputDataStream.map(new MapFunction<String, SensorReading>() {
  15. @Override
  16. public SensorReading map(String value) throws Exception {
  17. String[] fields = value.split(",");
  18. return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
  19. }
  20. });
  21. // 3.******测试ProcessFunction,自定义侧输出流实现分流操作******
  22. // 3.1 定义一个OutPutTag , 用来定义表示侧输出流-低温流
  23. OutputTag<SensorReading> lowOutputTag = new OutputTag<SensorReading>("lowSensor"){};
  24. // 3.2 自定义侧输出流实现分流操作
  25. SingleOutputStreamOperator<SensorReading> highSensorStream = dataStream.process(new ProcessFunction<SensorReading, SensorReading>() {
  26. @Override
  27. public void processElement(SensorReading sensorReading, Context context, Collector<SensorReading> collector) throws Exception {
  28. // 判断温度 大于 30 高温流
  29. if (sensorReading.getSensor() > 30) {
  30. collector.collect(sensorReading);
  31. } else {
  32. // 温度 小于 30 低温流
  33. context.output(lowOutputTag,sensorReading);
  34. }
  35. }
  36. });
  37. // 3.3 打印高温流
  38. highSensorStream.print("high-sensor");
  39. // 3.4 获取并打印低温流
  40. DataStream<SensorReading> lowSensorStream = highSensorStream.getSideOutput(lowOutputTag);
  41. lowSensorStream.print("low-sensor");
  42. // 4.执行(jobName)
  43. env.execute("ProcessFunction_SideOutPutDemo");
  44. }
  45. }

4.3 案例三(CoProcessFunction)

对于两条输入流,DataStream API 提供了 CoProcessFunction 这样的 low-level操作。CoProcessFunction 提供了操作每一个输入流的方法: processElement1()和processElement2()。

类似于 ProcessFunction,这两个方法都通过 Context 对象来调用。这个 Context对象可以访问事件数据,定时器时间戳,TimerService,以及 side outputs。CoProcessFunction 也提供了 onTimer()回调函数。

需求:在4.2 案例二基础上合并两条流(略)