1. ProcessFunction definition

The ProcessFunction function is a low-order stream processing operator that has access to all of the (non-cyclic) basic building blocks of a stream application:

  • Events (data flow elements)
  • State (fault tolerance and consistency, keyed Stream only)
  • Timer (event time and processing time, only for Keyed Stream)

ProcessFunction can be thought of as a FlatMapFunction that provides access to KeyedState and timers. This function is called every time an event is received in the input stream.

For fault-tolerant states, ProcessFunction can access KeyedState through RuntimeContext, similar to how other stateful functions access KeyedState.

Timers can handle changes in processing time and event time. Each call to processElement() gives you a Context object through which you can access the element’s event timestamp and TimerService. TimerService can register callbacks for event time/processing time instances that have not yet occurred. The onTimer() method is called when the timer reaches a certain point. During the call, all states are again limited to the keys created by the timer, allowing the timer to operate on KeyedState.

If you want to access the KeyedState and timer, you must use ProcessFunction on the KeyedStream.

2. Built-in ProcessFunction

  • ProcessFunction: used to DataStream
  • KeyedProcessFunction: for stream processing after KeyedStream, keyBy
  • CoProcessFunction: Streams used for connect connections
  • ProcessJoinFunction: Is used to operate the join flow
  • BroadcastProcessFunction: Used for broadcasting
  • KeyedBroadcastProcessFunction: Broadcast after keyBy
  • ProcessWindowFunction: Window increment aggregation
  • ProcessAllWindowFunction: Full-window aggregation

ProcessFunction is regarded as a FlatMapFunction with key state and timer access. For each event received in the input stream, this function is called to handle the event.

If you want to access keyed state and timer during stream processing, you must apply ProcessFunction to a Keyed stream as follows:

stream.keyBy(...) .process(new MyProcessFunction())
Copy the code

3. Example

As an extension (that is, a subclass) of ProcessFunction, KeyedProcessFunction performs the following functions in its onTimer(…) Method to provide access to the timer key. The template code is as follows:

@Override
public void onTimer(long timestamp, OnTimerContext ctx, Collector<OUT> out) throws Exception {
    K key = ctx.getCurrentKey();
    // ...
}
Copy the code

In the following example, KeyedProcessFunction maintains the count for each key and issues a key/count pair every time a minute passes (at event time) without updating the key:

  1. The count, key, and last-modify-timestamp are stored in a ValueState whose scope is implicitly determined by the key.
  2. For each record, KeyedProcessFunction increments the counter and sets the last modification timestamp.
  3. The function also schedules a callback one minute later (at event time).
  4. On each callback, it checks the callback’s event time timestamp against the last modification time of the stored count and issues a key/count when they match (that is, no further updates were made in that minute).

Example: Maintain a count for each key in the data flow and issue a key/count pair for every minute that passes (at event time) without updating the key.

1) Import the required dependencies first

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor;
import org.apache.flink.util.Collector;
Copy the code

2) Define the data structure (data model) for storing state data

/** * Data types stored in the state */
public class CountWithTimestamp {

	public String key;           / / store the key
	public long count;           // Store the count value
	public long lastModified;    // Time of last modification
}
Copy the code

3) Custom ProcessFunction, inherited from KeyedProcessFunction:

public class CountWithTimeoutFunction
		extends KeyedProcessFunction<Tuple.Tuple2<String.String>, Tuple2<String.Long>> {

	/** The state that is maintained by this handler */
	private ValueState<CountWithTimestamp> state;

	// First get the state maintained by the process function
        // Access the keyed state of Flink through RuntimeContext
	@Override
	public void open(Configuration parameters) throws Exception {
		state = getRuntimeContext().getState(new ValueStateDescriptor<>("myState", CountWithTimestamp.class));
	}

	// For each event received in the input stream, this function is called to handle the event
	For each record, KeyedProcessFunction increments the counter and sets the last modification timestamp
	@Override
	public void processElement( Tuple2
       
         value, Context ctx, Collector
        
         > out)
        ,> throws Exception {

		// Get the current count
		CountWithTimestamp current = state.value();
		if (current == null) {
			current = new CountWithTimestamp();
			current.key = value.f0;
		}

		// Update the status count
		current.count++;

		// Set the timestamp of this state to the assigned event timestamp of the record
                if(ctx ! =null) {
                	current.lastModified = ctx.timestamp();
                }

                // Write the state back
		state.update(current);

		// Schedule the next timer 60 seconds from the current event time
		ctx.timerService().registerEventTimeTimer(current.lastModified + 60000);
		}

	// Issue a key/count pair if there is no further update in one minute
	@Override
	public void onTimer(
			long timestamp,
			OnTimerContext ctx,
			Collector<Tuple2<String, Long>> out) throws Exception {

		// Get the state of the key that schedules this timer
		CountWithTimestamp result = state.value();

		// Check whether this is an outdated timer or the latest timer
		if (timestamp == result.lastModified + 60000) {
			// Issue status on timeout
			out.collect(newTuple2<String, Long>(result.key, result.count)); }}}Copy the code

4) Apply custom handlers to the main method of stream processing

public class StreamingJob {
    public static void main(String[] args) throws Exception {
	// Set the flow execution environment
	final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

	// By default, Flink will use processing time. To change this, you can set the time signature:
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        // The source data stream
        DataStream<Tuple2<String, String>> stream = env
                .fromElements("good good study"."day day up"."you see see you")
                .flatMap(new FlatMapFunction<String, Tuple2<String,String>>() {
                    @Override
                    public void flatMap(String line, Collector<Tuple2<String, String>> collector) throws Exception {
                        for(String word : line.split("\\W+")){
                            collector.collect(new Tuple2<>(word,"1")); }}});// Since the simulated data does not have a timestamp, use this method to add a timestamp and watermark
        DataStream<Tuple2<String, String>> withTimestampsAndWatermarks =
                stream.assignTimestampsAndWatermarks(new AscendingTimestampExtractor<Tuple2<String, String>>() {
                    @Override
                    public long extractAscendingTimestamp(Tuple2<String, String> element) {
                        returnSystem.currentTimeMillis(); }});// Use this function on keyed Stream
	DataStream<Tuple2<String, Long>> result = withTimestampsAndWatermarks.keyBy(0).process(new CountWithTimeoutFunction());

	// Output view
        result.print();

	// Execute the flow program
	env.execute("Process Function"); }}Copy the code