Flink – process watermark

本文详细解析了Flink中WindowOperator的工作原理,包括如何处理元素、触发窗口、注册定时器以及处理水位线等关键步骤。通过深入探讨内部机制,帮助读者理解Flink窗口处理的实现细节。

WindowOperator.processElement

主要的工作,将当前的element的value加到对应的window中,

            windowState.setCurrentNamespace(window);
            windowState.add(element.getValue());

            triggerContext.key = key;
            triggerContext.window = window;

            TriggerResult triggerResult = triggerContext.onElement(element);

 

调用triggerContext.onElement

这里的Context只是一个简单的封装,

        public TriggerResult onElement(StreamRecord<IN> element) throws Exception {
            return trigger.onElement(element.getValue(), element.getTimestamp(), window, this);
        }

 

EventTimeTrigger

onElement

    @Override
    public TriggerResult onElement(Object element, long timestamp, TimeWindow window, TriggerContext ctx) throws Exception {
        if (window.maxTimestamp() <= ctx.getCurrentWatermark()) {
            // if the watermark is already past the window fire immediately
            return TriggerResult.FIRE;
        } else {
            ctx.registerEventTimeTimer(window.maxTimestamp());
            return TriggerResult.CONTINUE;
        }
    }

如果当前window.maxTimestamp已经小于CurrentWatermark,直接触发

否则将window.maxTimestamp注册到TimeService中,等待触发

 

WindowOperator.Context

        public void registerEventTimeTimer(long time) {
            internalTimerService.registerEventTimeTimer(window, time);
        }

 

InternalTimerService
 
在AbstractStreamOperator
public abstract class AbstractStreamOperator<OUT>
        implements StreamOperator<OUT>, Serializable, KeyContext {
注意这里实现了KeyContext 
所以AbstractStreamOperator实现了
    public Object getCurrentKey() {
        if (keyedStateBackend != null) {
            return keyedStateBackend.getCurrentKey();
        } else {
            throw new UnsupportedOperationException("Key can only be retrieven on KeyedStream.");
        }
    }
 
在AbstractStreamOperator初始化InternalTimeServiceManager
private transient InternalTimeServiceManager<?, ?> timeServiceManager;
@Override
    public final void initializeState(OperatorStateHandles stateHandles) throws Exception {

        if (getKeyedStateBackend() != null && timeServiceManager == null) {
            timeServiceManager = new InternalTimeServiceManager<>(
                getKeyedStateBackend().getNumberOfKeyGroups(),
                getKeyedStateBackend().getKeyGroupRange(),
                this,
                getRuntimeContext().getProcessingTimeService());
        }

 

WindowOperator中InternalTimerService初始化,
internalTimerService =
getInternalTimerService("window-timers", windowSerializer, this);

在AbstractStreamOperator调用,

    public <K, N> InternalTimerService<N> getInternalTimerService(
            String name,
            TypeSerializer<N> namespaceSerializer,
            Triggerable<K, N> triggerable) {

        checkTimerServiceInitialization();

        // the following casting is to overcome type restrictions.
        TypeSerializer<K> keySerializer = (TypeSerializer<K>) getKeyedStateBackend().getKeySerializer();
        InternalTimeServiceManager<K, N> keyedTimeServiceHandler = (InternalTimeServiceManager<K, N>) timeServiceManager;
        return keyedTimeServiceHandler.getInternalTimerService(name, keySerializer, namespaceSerializer, triggerable);
    }

其实就是调用InternalTimeServiceManager.getInternalTimerService

最终得到HeapInternalTimerService

 

HeapInternalTimerService.registerEventTimeTimer
    @Override
    public void registerEventTimeTimer(N namespace, long time) {
        InternalTimer<K, N> timer = new InternalTimer<>(time, (K) keyContext.getCurrentKey(), namespace);
        Set<InternalTimer<K, N>> timerSet = getEventTimeTimerSetForTimer(timer);
        if (timerSet.add(timer)) {
            eventTimeTimersQueue.add(timer);
        }
    }

创建InternalTimer,包含,time(window.maxTimestamp), key(keyContext.getCurrentKey), namespace(window)

 

getEventTimeTimerSetForTimer

    private Set<InternalTimer<K, N>> getEventTimeTimerSetForTimer(InternalTimer<K, N> timer) {
        checkArgument(localKeyGroupRange != null, "The operator has not been initialized.");
        int keyGroupIdx = KeyGroupRangeAssignment.assignToKeyGroup(timer.getKey(), this.totalKeyGroups);
        return getEventTimeTimerSetForKeyGroup(keyGroupIdx);
    }

    private Set<InternalTimer<K, N>> getEventTimeTimerSetForKeyGroup(int keyGroupIdx) {
        int localIdx = getIndexForKeyGroup(keyGroupIdx);
        Set<InternalTimer<K, N>> timers = eventTimeTimersByKeyGroup[localIdx];
        if (timers == null) {
            timers = new HashSet<>();
            eventTimeTimersByKeyGroup[localIdx] = timers;
        }
        return timers;
    }

先找到key所对应的,keygroup,每个keygroup对应于一个Timer集合

这样设计的目的,因为最终timer也是要checkpoint的,而checkpoint的最小单位是keygroup,所以不同keygroup所对应的timer需要分离开

最终把timer加到eventTimeTimersQueue,

private final PriorityQueue<InternalTimer<K, N>> eventTimeTimersQueue;

PriorityQueue是堆实现的,所以只要在InternalTimer里面实现compareTo,就可以让timer排序

AbstractStreamOperator.processWatermark

   public void processWatermark(Watermark mark) throws Exception {
        if (timeServiceManager != null) {
            timeServiceManager.advanceWatermark(mark);
        }
        output.emitWatermark(mark);
    }

timeServiceManager.advanceWatermark

    public void advanceWatermark(Watermark watermark) throws Exception {
        for (HeapInternalTimerService<?, ?> service : timerServices.values()) {
            service.advanceWatermark(watermark.getTimestamp());
        }
    }

HeapInternalTimerService.advanceWatermark

    public void advanceWatermark(long time) throws Exception {
        currentWatermark = time;

        InternalTimer<K, N> timer;

        while ((timer = eventTimeTimersQueue.peek()) != null && timer.getTimestamp() <= time) {

            Set<InternalTimer<K, N>> timerSet = getEventTimeTimerSetForTimer(timer);
            timerSet.remove(timer);
            eventTimeTimersQueue.remove();

            keyContext.setCurrentKey(timer.getKey());
            triggerTarget.onEventTime(timer);
        }
    }

从eventTimeTimersQueue从小到大取timer,如果小于传入的water mark,那么说明这个window需要触发

设置operater的current key,keyContext.setCurrentKey(timer.getKey())

这里注意watermarker是没有key的,所以当一个watermark来的时候是会触发所有timer,而timer的key是不一定的,所以这里一定要设置keyContext,否则就乱了

最终触发triggerTarget.onEventTime

triggerTarget就是WindowOperator

WindowOperator.onEventTime

        windowState.setCurrentNamespace(triggerContext.window);

        ACC contents = null;
        if (windowState != null) {
            contents = windowState.get();
        }

        if (contents != null) {
            TriggerResult triggerResult = triggerContext.onEventTime(timer.getTimestamp());
            if (triggerResult.isFire()) {
                emitWindowContents(triggerContext.window, contents);
            }
            if (triggerResult.isPurge()) {
                windowState.clear();
            }
        }

这里调用triggerContext.onEventTime,得到TriggerResult

如果fire,走到这,这个肯定满足的,emitWindowContents

如果purge,就把windowState清空

emitWindowContents,调用用户定义的windowFunction来处理window的contents

    private void emitWindowContents(W window, ACC contents) throws Exception {
        timestampedCollector.setAbsoluteTimestamp(window.maxTimestamp());
        processContext.window = window;
        userFunction.process(triggerContext.key, window, processContext, contents, timestampedCollector);
    }

转载于:https://www.cnblogs.com/fxjwind/p/7657058.html

### FlinkProcessFunction 的功能和作用 #### 1. **ProcessFunction 的基本概念** `ProcessFunction` 是 Apache Flink 提供的一种低级 API,用于对 DataStream 进行更加灵活和细粒度的操作。它允许开发者通过自定义逻辑来处理每个元素,并支持时间相关的操作[^1]。 在实际应用中,`ProcessFunction` 可以被看作是对传统转换操作(如 `map()` 或 `filter()`)的一个扩展版本。它的主要特点是能够提供对时间和状态的控制能力,这是其他高级算子无法做到的[^3]。 --- #### 2. **核心方法解析** ##### (1) **processElement 方法** 该方法会在流中的每一个元素到达时被调用。其签名如下: ```java public abstract void processElement(I value, Context ctx, Collector<O> out) throws Exception; ``` - 参数说明: - `value`: 当前正在处理的数据元素。 - `ctx`: 上下文对象,提供了关于当前元素的信息,比如时间戳、键值以及 TimerService 时间服务接口。 - `out`: 输出收集器,用于将结果发送到下游。 此方法的主要用途是在单个记录级别执行复杂的业务逻辑,同时还能利用上下文中提供的额外工具完成更多任务,例如向侧输出流写入数据[^5]。 --- ##### (2) **onTimer 方法** 这是一个回调函数,在之前注册的定时器触发时会被自动调用。其签名为: ```java public void onTimer(long timestamp, OnTimerContext ctx, Collector<O> out) throws Exception {} ``` - 参数解释: - `timestamp`: 定时器设置的目标时间戳。 - `ctx`: 类似于 `processElement` 中的上下文,包含了有关定时器触发时刻的相关细节。 - `out`: 同样是一个输出收集器实例,负责传递计算后的成果给后续阶段。 借助这一特性,用户可以在特定条件下延迟某些动作的发生,从而实现诸如窗口聚合之外更为精细的时间管理需求[^4]。 --- #### 3. **使用场景分析** 由于具备强大的灵活性与可控性,因此适用于多种复杂场景下的实时数据分析工作负载。以下是几个典型的应用方向: - **获取 WatermarkProcessing Time**: 如果应用程序需要感知输入序列里隐含的时间线索,则可通过访问 `ctx.timestamp()` 获取相应数值;而要读取系统运行期间的实际钟表刻度则需依赖 `TimerService.currentProcessingTime()` 函数。 - **跨时间段关联查询**: 借助内置计时机制安排未来某个瞬间重新审视现存条件变化情况的能力,使得解决涉及历史回溯型难题成为可能。 - **多路分流传输**: 利用 side outputs 功能把不符合常规路径走向的数据另辟蹊径送往专门通道进一步处置。 --- #### 4. **代码示例展示** 下面给出一段简单的 Java 实现片段演示如何运用上述理论构建解决方案框架: ```java stream.keyBy((KeySelector<MyEvent, String>) event -> event.getKey()) .process(new KeyedProcessFunction<String, MyEvent, String>() { @Override public void processElement(MyEvent value, Context ctx, Collector<String> out) throws Exception { // 处理每条进入的消息并决定是否立即发出响应还是稍后再做判断 long currentTime = ctx.timerService().currentProcessingTime(); if (shouldEmitNow(value)) { out.collect("Immediate result for " + value); } else { ctx.timerService().registerProcessingTimeTimer(currentTime + DELAY_MS); } } @Override public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception { // 在预定时间点检查是否有待决事项需要通知外界知晓 out.collect("Delayed action triggered at " + new Timestamp(timestamp)); } }); ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值