• 基本处理函数(ProcessFunction)


    处理函数主要是定义数据流的转换操作,所以也可以把它归到转换算子中。在Flink中几乎所有转换算子都提供了对应的函数类接口,处理函数也不例外;它所对应的函数类,就叫作ProcessFunction。

    1、处理函数的功能和使用

    之前学习的转换算子,一般只是针对某种具体操作来定义的,能够拿到的信息比较有限。比如map算子,实现的MapFunction中,只能获取到当前的数据,定义它转换之后的形式;而像窗口聚合这样的复杂操作,AggregateFunction中除数据外,还可以获取到当前的状态(以累加器Accumulator形式出现)。另外还介绍过富函数类,比如RichMapFunction,它提供了获取运行时上下文的方法getRuntimeContext(),可以拿到状态,还有并行度、任务名称之类的运行时信息。但是无论那种算子,如果想要访问事件的时间戳,或者当前的水位线信息,都是完全做不到的。在定义生成规则之后,水位线会源源不断地产生,像数据一样在任务间流动,却不能像数据一样去处理它;跟时间相关的操作,目前只会用窗口来处理。而在很多应用需求中,要求对时间有更精细的控制,需要能够获取水位线,甚至要“把控时间”、定义什么时候做什么事,这就不是基本的时间窗口能够实现的了。于是必须祭出大招——处理函数(ProcessFunction)了。处理函数提供了一个“定时服务”(TimerService),可以通过它访问流中的事件(event)、时间戳(timestamp)、水位线(watermark),甚至可以注册“定时事件”。而且处理函数继承了AbstractRichFunction抽象类,所以拥有富函数类的所有特性,同样可以访问状态(state)和其他运行时信息。此外,处理函数还可以直接将数据输出到侧输出流(sideoutput)中。所以,处理函数是最为灵活的处理方法,可以实现各种自定义的业务逻辑;同时也是整个DataStreamAPI的底层基础。处理函数的使用与基本的转换操作类似,只需要直接基于DataStream调用.process()方法就可以了。方法需要传入一个ProcessFunction作为参数,用来定义处理逻辑。
    public class ProcessFunctionTest {
        public static void main(String[] args) throws Exception {
            StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
            SingleOutputStreamOperator<Event> eventDS = env.addSource(new ClickSource())
                    .assignTimestampsAndWatermarks(
                            WatermarkStrategy
                                    .<Event>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                                    .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                                        @Override
                                        public long extractTimestamp(Event element, long recordTimestamp) {
                                            return element.timestamp;
                                        }
                                    }));
    
            eventDS.process(new ProcessFunction<Event, String>() {
                @Override
                public void processElement(Event value, Context ctx, Collector<String> out) throws Exception {
                    if (value.user.equals("依琳")) {
                        out.collect(value.user + " clicks " + value.url);
                    } else if (value.user.equals("令狐冲")) {
                        out.collect(value.user);
                        out.collect(value.user); 
    }
    System.out.println(
    "timestamp - > "+ctx.timestamp());
    System.out.println(
    "currentWatermark - > "+ctx.timerService().currentWatermark()); } }).print(); env.execute();
    }
    }

    这里在ProcessFunction中重写了.processElement()方法,自定义了一种处理逻辑:当数据的user为“依琳”时,将其输出一次;而如果为“令狐冲”时,将user输出两次。这里的输 出 , 是 通 过 调 用out.collect()来实现的。另外我们还可以调用ctx.timerService().currentWatermark()来获取当前的水位线打印输出。所以可以看到,ProcessFunction函数有点像FlatMapFunction的升级版。可以实现Map、Filter、FlatMap的所有功能。很明显,处理函数非常强大,能够做很多之前做不到的事情。

    2、ProcessFunction解析

    在源码中我们可以看到,抽象类ProcessFunction继承了AbstractRichFunction,有两个泛型类型参数:I表示Input,也就是输入的数据类型;O表示Output,也就是处理完成之后输出的数据类型。内部单独定义了两个方法:一个是必须要实现的抽象方法.processElement();另一个是非抽象方法.onTimer()。 
    @PublicEvolving
    public abstract class ProcessFunction<I, O> extends AbstractRichFunction {
    
        private static final long serialVersionUID = 1L;
    
        /**
         * Process one element from the input stream.
         *
         * <p>This function can output zero or more elements using the {@link Collector} parameter and
         * also update internal state or set timers using the {@link Context} parameter.
         *
         * @param value The input value.
         * @param ctx A {@link Context} that allows querying the timestamp of the element and getting a
         *     {@link TimerService} for registering timers and querying the time. The context is only
         *     valid during the invocation of this method, do not store it.
         * @param out The collector for returning result values.
         * @throws Exception This method may throw exceptions. Throwing an exception will cause the
         *     operation to fail and may trigger recovery.
         */
        public abstract void processElement(I value, Context ctx, Collector<O> out) throws Exception;
    
        /**
         * Called when a timer set using {@link TimerService} fires.
         *
         * @param timestamp The timestamp of the firing timer.
         * @param ctx An {@link OnTimerContext} that allows querying the timestamp of the firing timer,
         *     querying the {@link TimeDomain} of the firing timer and getting a {@link TimerService}
         *     for registering timers and querying the time. The context is only valid during the
         *     invocation of this method, do not store it.
         * @param out The collector for returning result values.
         * @throws Exception This method may throw exceptions. Throwing an exception will cause the
         *     operation to fail and may trigger recovery.
         */
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<O> out) throws Exception {}
    
        /**
         * Information available in an invocation of {@link #processElement(Object, Context, Collector)}
         * or {@link #onTimer(long, OnTimerContext, Collector)}.
         */
        public abstract class Context {
    
            /**
             * Timestamp of the element currently being processed or timestamp of a firing timer.
             *
             * <p>This might be {@code null}, for example if the time characteristic of your program is
             * set to {@link org.apache.flink.streaming.api.TimeCharacteristic#ProcessingTime}.
             */
            public abstract Long timestamp();
    
            /** A {@link TimerService} for querying time and registering timers. */
            public abstract TimerService timerService();
    
            /**
             * Emits a record to the side output identified by the {@link OutputTag}.
             *
             * @param outputTag the {@code OutputTag} that identifies the side output to emit to.
             * @param value The record to emit.
             */
            public abstract <X> void output(OutputTag<X> outputTag, X value);
        }
    
        /**
         * Information available in an invocation of {@link #onTimer(long, OnTimerContext, Collector)}.
         */
        public abstract class OnTimerContext extends Context {
            /** The {@link TimeDomain} of the firing timer. */
            public abstract TimeDomain timeDomain();
        }
    }

    抽象方法.processElement()

    用于“处理元素”,定义了处理的核心逻辑。这个方法对于流中的每个元素都会调用一次,参数包括三个:输入数据值value,上下文ctx,以及“收集器”(Collector)out。方法没有返回值,处理之后的输出数据是通过收集器out来定义的
    value:当前流中的输入元素,也就是正在处理的数据,类型与流中数据类型一致。
    ctx:类型是ProcessFunction中定义的内部抽象类Context,表示当前运行的上下文,可以获取到当前的时间戳,
    并提供了用于查询时间和注册定时器的“定时服务”(TimerService),以及可以将数据发送到“侧输出流”(side output)的方法.output()。Context抽象类定义如下:
    out:“收集器”(类型为Collector),用于返回输出数据。使用方式与flatMap算子中的收集器完全一样,直接调用out.collect()方法就可以向下游发出一个数据。这个方法可以多次调用,也可以不调用。
     /**
         * Information available in an invocation of {@link #processElement(Object, Context, Collector)}
         * or {@link #onTimer(long, OnTimerContext, Collector)}.
         */
        public abstract class Context {
    
            /**
             * Timestamp of the element currently being processed or timestamp of a firing timer.
             *
             * <p>This might be {@code null}, for example if the time characteristic of your program is
             * set to {@link org.apache.flink.streaming.api.TimeCharacteristic#ProcessingTime}.
             */
            public abstract Long timestamp();
    
            /** A {@link TimerService} for querying time and registering timers. */
            public abstract TimerService timerService();
    
            /**
             * Emits a record to the side output identified by the {@link OutputTag}.
             *
             * @param outputTag the {@code OutputTag} that identifies the side output to emit to.
             * @param value The record to emit.
             */
            public abstract <X> void output(OutputTag<X> outputTag, X value);
        }

    通过几个参数的分析不难发现,ProcessFunction可以轻松实现flatMap这样的基本转换功能(当然map、filter更不在话下);而通过富函数提供的获取上下文方法.getRuntimeContext(),也可以自定义状态(state)进行处理,这也就能实现聚合操作的功能了。

    非抽象方法.onTimer()

    用于定义定时触发的操作,这是一个非常强大、也非常有趣的功能。这个方法只有在注册好的定时器触发的时候才会调用,而定时器是通过“定时服务”TimerService来注册的。打个比方,注册定时器(timer)就是设了一个闹钟,到了设定时间就会响;而.onTimer()中定义的,就是闹钟响的时候要做的事。所以它本质上是一个基于时间的“回调”(callback)方法,通过时间的进展来触发;在事件时间语义下就是由水位线(watermark)来触发了。与.processElement()类似,定时方法.onTimer()也有三个参数:时间戳(timestamp),上下文(ctx),以及收集器(out)。这里的timestamp是指设定好的触发时间,事件时间语义下当然就是水位线了。另外这里同样有上下文和收集器,所以也可以调用定时服务(TimerService),以及任意输出处理之后的数据。既然有.onTimer()方法做定时触发,用ProcessFunction也可以自定义数据按照时间分组、定时触发计算输出结果;这其实就实现了窗口(window)的功能。所以说ProcessFunction是真正意义上的终极奥义,用它可以实现一切功能。我们也可以看到,处理函数都是基于事件触发的。水位线就如同插入流中的一条数据一样;只不过处理真正的数据事件调用的是.processElement()方法,而处理水位线事件调用的是.onTimer()。这里需要注意的是,上面的.onTimer()方法只是定时器触发时的操作,而定时器(timer)真正的设置需要用到上下文ctx中的定时服务。在Flink中,只有“按键分区流”KeyedStream才支持设置定时器的操作,所以之前的代码中我们并没有使用定时器。所以基于不同类型的流,可以使用不同的处理函数,它们之间还是有一些微小的区别的。接下来我们就介绍一下处理函数的分类。 
  • 相关阅读:
    机器学习之KNN算法学习笔记
    机器学习之决策树算法学习笔记
    RNN神经网络
    深度学习笔记-Tensorflow(一)
    CNN卷积神经网络-tensorflow
    个人喜欢的网址
    CSP2020游记
    题解 GDFZOJ 2020普转提十连测day5
    讲义 GDFZOJ 【38】 动态规划基础3
    题解 GDFZOJ 【2314】 东风谷早苗
  • 原文地址:https://www.cnblogs.com/wdh01/p/16443876.html
Copyright © 2020-2023  润新知