Flink – Trigger,Evictor

本文涉及的产品
实时计算 Flink 版,1000CU*H 3个月
简介:
org.apache.flink.streaming.api.windowing.triggers;

 

Trigger

复制代码
public abstract class Trigger<T, W extends Window> implements Serializable {

    /**
     * Called for every element that gets added to a pane. The result of this will determine
     * whether the pane is evaluated to emit results.
     *
     * @param element The element that arrived.
     * @param timestamp The timestamp of the element that arrived.
     * @param window The window to which the element is being added.
     * @param ctx A context object that can be used to register timer callbacks.
     */
    public abstract TriggerResult onElement(T element, long timestamp, W window, TriggerContext ctx) throws Exception;

    /**
     * Called when a processing-time timer that was set using the trigger context fires.
     *
     * @param time The timestamp at which the timer fired.
     * @param window The window for which the timer fired.
     * @param ctx A context object that can be used to register timer callbacks.
     */
    public abstract TriggerResult onProcessingTime(long time, W window, TriggerContext ctx) throws Exception;

    /**
     * Called when an event-time timer that was set using the trigger context fires.
     *
     * @param time The timestamp at which the timer fired.
     * @param window The window for which the timer fired.
     * @param ctx A context object that can be used to register timer callbacks.
     */
    public abstract TriggerResult onEventTime(long time, W window, TriggerContext ctx) throws Exception;

    /**
     * Called when several windows have been merged into one window by the
     * {@link org.apache.flink.streaming.api.windowing.assigners.WindowAssigner}.
     *
     * @param window The new window that results from the merge.
     * @param ctx A context object that can be used to register timer callbacks and access state.
     */
    public TriggerResult onMerge(W window, OnMergeContext ctx) throws Exception {
        throw new RuntimeException("This trigger does not support merging.");
    }
复制代码

Trigger决定pane何时被evaluated,实现一系列接口,来判断各种情况下是否需要trigger

看看具体的trigger的实现,

ProcessingTimeTrigger

复制代码
/**
 * A {@link Trigger} that fires once the current system time passes the end of the window
 * to which a pane belongs.
 */
public class ProcessingTimeTrigger implements Trigger<Object, TimeWindow> {
    private static final long serialVersionUID = 1L;
    
    private ProcessingTimeTrigger() {}
    
    @Override
    public TriggerResult onElement(Object element, long timestamp, TimeWindow window, TriggerContext ctx) {
        ctx.registerProcessingTimeTimer(window.maxTimestamp()); //对于processingTime,element的trigger时间是current+window,所以这里需要注册定时器去触发
        return TriggerResult.CONTINUE;
    }
    
    @Override
    public TriggerResult onEventTime(long time, TimeWindow window, TriggerContext ctx) throws Exception {
        return TriggerResult.CONTINUE;
    }
    
    @Override
    public TriggerResult onProcessingTime(long time, TimeWindow window, TriggerContext ctx) {//触发后调用
        return TriggerResult.FIRE_AND_PURGE;
    }
    
    @Override
    public String toString() {
        return "ProcessingTimeTrigger()";
    }
    
    /**
    * Creates a new trigger that fires once system time passes the end of the window.
    */
    public static ProcessingTimeTrigger create() {
        return new ProcessingTimeTrigger();
    }
}
复制代码

可以看到只有在onProcessingTime的时候,是FIRE_AND_PURGE,其他时候都是continue

再看个CountTrigger,

复制代码
public class CountTrigger<W extends Window> extends Trigger<Object, W> {

    private final long maxCount;

    private final ReducingStateDescriptor<Long> stateDesc =
            new ReducingStateDescriptor<>("count", new Sum(), LongSerializer.INSTANCE);

    private CountTrigger(long maxCount) {
        this.maxCount = maxCount;
    }

    @Override
    public TriggerResult onElement(Object element, long timestamp, W window, TriggerContext ctx) throws Exception {
        ReducingState<Long> count = ctx.getPartitionedState(stateDesc); //从backend取出conunt state
        count.add(1L); //加1
        if (count.get() >= maxCount) {
            count.clear();
            return TriggerResult.FIRE;
        }
        return TriggerResult.CONTINUE;
    }

    @Override
    public TriggerResult onEventTime(long time, W window, TriggerContext ctx) {
        return TriggerResult.CONTINUE;
    }

    @Override
    public TriggerResult onProcessingTime(long time, W window, TriggerContext ctx) throws Exception {
        return TriggerResult.CONTINUE;
    }

    @Override
    public TriggerResult onMerge(W window, OnMergeContext ctx) throws Exception {
        ctx.mergePartitionedState(stateDesc); //先调用merge,底层backend里面的window进行merge
        ReducingState<Long> count = ctx.getPartitionedState(stateDesc); //merge后再取出state,count,进行判断
        if (count.get() >= maxCount) {
            return TriggerResult.FIRE;
        }
        return TriggerResult.CONTINUE;
    }
复制代码

很简单,既然是算count,那么和time相关的自然都是continue

对于count,是在onElement中触发,每次来element都会走到这个逻辑

当累积的count > 设定的count时,就会返回Fire,注意,这里这是fire,并不会purge

并将计数清0

 

TriggerResult

TriggerResult是个枚举,

enum TriggerResult {
    CONTINUE(false, false), FIRE_AND_PURGE(true, true), FIRE(true, false), PURGE(false, true);
    
    private final boolean fire;
    private final boolean purge;
}

两个选项,fire,purge,2×2,所以4种可能性

两个Result可以merge,

复制代码
/**
 * Merges two {@code TriggerResults}. This specifies what should happen if we have
 * two results from a Trigger, for example as a result from
 * {@link Trigger#onElement(Object, long, Window, Trigger.TriggerContext)} and
 * {@link Trigger#onEventTime(long, Window, Trigger.TriggerContext)}.
 *
 * <p>
 * For example, if one result says {@code CONTINUE} while the other says {@code FIRE}
 * then {@code FIRE} is the combined result;
 */
public static TriggerResult merge(TriggerResult a, TriggerResult b) {
    if (a.purge || b.purge) {
        if (a.fire || b.fire) {
            return FIRE_AND_PURGE;
        } else {
            return PURGE;
        }
    } else if (a.fire || b.fire) {
        return FIRE;
    } else {
        return CONTINUE;
    }
}
复制代码

 

TriggerContext

为Trigger做些环境的工作,比如管理timer,和处理state

这些接口在,Trigger中的接口逻辑里面都会用到,所以在Trigger的所有接口上,都需要传入context

复制代码
/**
     * A context object that is given to {@link Trigger} methods to allow them to register timer
     * callbacks and deal with state.
     */
    public interface TriggerContext {

        long getCurrentProcessingTime();
        long getCurrentWatermark();
    
        /**
         * Register a system time callback. When the current system time passes the specified
         * time {@link Trigger#onProcessingTime(long, Window, TriggerContext)} is called with the time specified here.
         *
         * @param time The time at which to invoke {@link Trigger#onProcessingTime(long, Window, TriggerContext)}
         */
        void registerProcessingTimeTimer(long time);
        void registerEventTimeTimer(long time);
    
        void deleteProcessingTimeTimer(long time);
        void deleteEventTimeTimer(long time);
    

        <S extends State> S getPartitionedState(StateDescriptor<S, ?> stateDescriptor);
    }
复制代码

 

OnMergeContext 仅仅是多了一个接口,

public interface OnMergeContext extends TriggerContext {
    <S extends MergingState<?, ?>> void mergePartitionedState(StateDescriptor<S, ?> stateDescriptor);
}

 

WindowOperator.Context作为TriggerContext的一个实现,

复制代码
/**
 * {@code Context} is a utility for handling {@code Trigger} invocations. It can be reused
 * by setting the {@code key} and {@code window} fields. No internal state must be kept in
 * the {@code Context}
 */
public class Context implements Trigger.OnMergeContext {
    protected K key; //Context对应的window上下文
    protected W window;

    protected Collection<W> mergedWindows; //onMerge中被赋值

    @SuppressWarnings("unchecked")
    public <S extends State> S getPartitionedState(StateDescriptor<S, ?> stateDescriptor) {
        try {
            return WindowOperator.this.getPartitionedState(window, windowSerializer, stateDescriptor); //从backend里面读出改window的状态,即window buffer
        } catch (Exception e) {
            throw new RuntimeException("Could not retrieve state", e);
        }
    }

    @Override
    public <S extends MergingState<?, ?>> void mergePartitionedState(StateDescriptor<S, ?> stateDescriptor) {
        if (mergedWindows != null && mergedWindows.size() > 0) {
            try {
                WindowOperator.this.getStateBackend().mergePartitionedStates(window, //在backend层面把mergedWindows merge到window中
                        mergedWindows,
                        windowSerializer,
                        stateDescriptor);
            } catch (Exception e) {
                throw new RuntimeException("Error while merging state.", e);
            }
        }
    }

    @Override
    public void registerProcessingTimeTimer(long time) {
        Timer<K, W> timer = new Timer<>(time, key, window);
        // make sure we only put one timer per key into the queue
        if (processingTimeTimers.add(timer)) {
            processingTimeTimersQueue.add(timer);
            //If this is the first timer added for this timestamp register a TriggerTask
            if (processingTimeTimerTimestamps.add(time, 1) == 0) { //如果这个window是第一次注册的话
                ScheduledFuture<?> scheduledFuture = WindowOperator.this.registerTimer(time, WindowOperator.this); //对于processTime必须注册定时器主动触发
                processingTimeTimerFutures.put(time, scheduledFuture);
            }
        }
    }

    @Override
    public void registerEventTimeTimer(long time) {
        Timer<K, W> timer = new Timer<>(time, key, window);
        if (watermarkTimers.add(timer)) {
            watermarkTimersQueue.add(timer);
        }
    }

    //封装一遍trigger的接口,并把self作为context传入trigger的接口中
    public TriggerResult onElement(StreamRecord<IN> element) throws Exception {
        return trigger.onElement(element.getValue(), element.getTimestamp(), window, this);
    }

    public TriggerResult onProcessingTime(long time) throws Exception {
        return trigger.onProcessingTime(time, window, this);
    }

    public TriggerResult onEventTime(long time) throws Exception {
        return trigger.onEventTime(time, window, this);
    }

    public TriggerResult onMerge(Collection<W> mergedWindows) throws Exception {
        this.mergedWindows = mergedWindows;
        return trigger.onMerge(window, this);
    }

}

 
复制代码

 

Evictor

复制代码
/**
 * An {@code Evictor} can remove elements from a pane before it is being processed and after
 * window evaluation was triggered by a
 * {@link org.apache.flink.streaming.api.windowing.triggers.Trigger}.
 *
 * <p>
 * A pane is the bucket of elements that have the same key (assigned by the
 * {@link org.apache.flink.api.java.functions.KeySelector}) and same {@link Window}. An element can
 * be in multiple panes of it was assigned to multiple windows by the
 * {@link org.apache.flink.streaming.api.windowing.assigners.WindowAssigner}. These panes all
 * have their own instance of the {@code Evictor}.
 *
 * @param <T> The type of elements that this {@code Evictor} can evict.
 * @param <W> The type of {@link Window Windows} on which this {@code Evictor} can operate.
 */
public interface Evictor<T, W extends Window> extends Serializable {

    /**
     * Computes how many elements should be removed from the pane. The result specifies how
     * many elements should be removed from the beginning.
     *
     * @param elements The elements currently in the pane.
     * @param size The current number of elements in the pane.
     * @param window The {@link Window}
     */
    int evict(Iterable<StreamRecord<T>> elements, int size, W window);
}
复制代码

Evictor的目的就是在Trigger fire后,但在element真正被处理前,从pane中remove掉一些数据

比如你虽然是每小时触发一次,但是只是想处理最后10分钟的数据,而不是所有数据。。。

 

CountEvictor

复制代码
/**
 * An {@link Evictor} that keeps only a certain amount of elements.
 *
 * @param <W> The type of {@link Window Windows} on which this {@code Evictor} can operate.
 */
public class CountEvictor<W extends Window> implements Evictor<Object, W> {
    private static final long serialVersionUID = 1L;
    
    private final long maxCount;
    
    private CountEvictor(long count) {
        this.maxCount = count;
    }
    
    @Override
    public int evict(Iterable<StreamRecord<Object>> elements, int size, W window) {
        if (size > maxCount) {
            return (int) (size - maxCount);
        } else {
            return 0;
        }
    }
    
    /**
    * Creates a {@code CountEvictor} that keeps the given number of elements.
    *
    * @param maxCount The number of elements to keep in the pane.
    */
    public static <W extends Window> CountEvictor<W> of(long maxCount) {
        return new CountEvictor<>(maxCount);
    }
}
复制代码

初始化count,表示想保留多少elements(from end)

evict返回需要删除的elements数目(from begining)

如果element数大于保留数,我们需要删除size – maxCount(from begining)

反之,就全保留

 

TimeEvictor

复制代码
/**
 * An {@link Evictor} that keeps elements for a certain amount of time. Elements older
 * than {@code current_time - keep_time} are evicted.
 *
 * @param <W> The type of {@link Window Windows} on which this {@code Evictor} can operate.
 */
public class TimeEvictor<W extends Window> implements Evictor<Object, W> {
    private static final long serialVersionUID = 1L;
    
    private final long windowSize;
    
    public TimeEvictor(long windowSize) {
        this.windowSize = windowSize;
    }
    
    @Override
    public int evict(Iterable<StreamRecord<Object>> elements, int size, W window) {
        int toEvict = 0;
        long currentTime = Iterables.getLast(elements).getTimestamp();
        long evictCutoff = currentTime - windowSize;
        for (StreamRecord<Object> record: elements) {
            if (record.getTimestamp() > evictCutoff) {
                break;
            }
            toEvict++;
        }
        return toEvict;
    }
}
复制代码

TimeEvictor设置需要保留的时间,

用最后一条的时间作为current,current-windowSize,作为界限,小于这个时间的要evict掉

这里的前提是,数据是时间有序的

相关实践学习
基于Hologres+Flink搭建GitHub实时数据大屏
通过使用Flink、Hologres构建实时数仓,并通过Hologres对接BI分析工具(以DataV为例),实现海量数据实时分析.
实时计算 Flink 实战课程
如何使用实时计算 Flink 搞定数据处理难题?实时计算 Flink 极客训练营产品、技术专家齐上阵,从开源 Flink功能介绍到实时计算 Flink 优势详解,现场实操,5天即可上手! 欢迎开通实时计算 Flink 版: https://cn.aliyun.com/product/bigdata/sc Flink Forward Asia 介绍: Flink Forward 是由 Apache 官方授权,Apache Flink Community China 支持的会议,通过参会不仅可以了解到 Flink 社区的最新动态和发展计划,还可以了解到国内外一线大厂围绕 Flink 生态的生产实践经验,是 Flink 开发者和使用者不可错过的盛会。 去年经过品牌升级后的 Flink Forward Asia 吸引了超过2000人线下参与,一举成为国内最大的 Apache 顶级项目会议。结合2020年的特殊情况,Flink Forward Asia 2020 将在12月26日以线上峰会的形式与大家见面。
相关文章
|
12月前
|
运维 数据处理 数据安全/隐私保护
阿里云实时计算Flink版测评报告
该测评报告详细介绍了阿里云实时计算Flink版在用户行为分析与标签画像中的应用实践,展示了其毫秒级的数据处理能力和高效的开发流程。报告还全面评测了该服务在稳定性、性能、开发运维及安全性方面的卓越表现,并对比自建Flink集群的优势。最后,报告评估了其成本效益,强调了其灵活扩展性和高投资回报率,适合各类实时数据处理需求。
|
存储 监控 大数据
阿里云实时计算Flink在多行业的应用和实践
本文整理自 Flink Forward Asia 2023 中闭门会的分享。主要分享实时计算在各行业的应用实践,对回归实时计算的重点场景进行介绍以及企业如何使用实时计算技术,并且提供一些在技术架构上的参考建议。
1329 7
阿里云实时计算Flink在多行业的应用和实践
|
10月前
|
存储 分布式计算 流计算
实时计算 Flash – 兼容 Flink 的新一代向量化流计算引擎
本文介绍了阿里云开源大数据团队在实时计算领域的最新成果——向量化流计算引擎Flash。文章主要内容包括:Apache Flink 成为业界流计算标准、Flash 核心技术解读、性能测试数据以及在阿里巴巴集团的落地效果。Flash 是一款完全兼容 Apache Flink 的新一代流计算引擎,通过向量化技术和 C++ 实现,大幅提升了性能和成本效益。
3155 73
实时计算 Flash – 兼容 Flink 的新一代向量化流计算引擎
zdl
|
10月前
|
消息中间件 运维 大数据
大数据实时计算产品的对比测评:实时计算Flink版 VS 自建Flink集群
本文介绍了实时计算Flink版与自建Flink集群的对比,涵盖部署成本、性能表现、易用性和企业级能力等方面。实时计算Flink版作为全托管服务,显著降低了运维成本,提供了强大的集成能力和弹性扩展,特别适合中小型团队和业务波动大的场景。文中还提出了改进建议,并探讨了与其他产品的联动可能性。总结指出,实时计算Flink版在简化运维、降低成本和提升易用性方面表现出色,是大数据实时计算的优选方案。
zdl
410 56
|
SQL 消息中间件 Kafka
实时计算 Flink版产品使用问题之如何在EMR-Flink的Flink SOL中针对source表单独设置并行度
实时计算Flink版作为一种强大的流处理和批处理统一的计算框架,广泛应用于各种需要实时数据处理和分析的场景。实时计算Flink版通常结合SQL接口、DataStream API、以及与上下游数据源和存储系统的丰富连接器,提供了一套全面的解决方案,以应对各种实时计算需求。其低延迟、高吞吐、容错性强的特点,使其成为众多企业和组织实时数据处理首选的技术平台。以下是实时计算Flink版的一些典型使用合集。
|
8月前
|
消息中间件 关系型数据库 MySQL
Flink CDC 在阿里云实时计算Flink版的云上实践
本文整理自阿里云高级开发工程师阮航在Flink Forward Asia 2024的分享,重点介绍了Flink CDC与实时计算Flink的集成、CDC YAML的核心功能及应用场景。主要内容包括:Flink CDC的发展及其在流批数据处理中的作用;CDC YAML支持的同步链路、Transform和Route功能、丰富的监控指标;典型应用场景如整库同步、Binlog原始数据同步、分库分表同步等;并通过两个Demo展示了MySQL整库同步到Paimon和Binlog同步到Kafka的过程。最后,介绍了未来规划,如脏数据处理、数据限流及扩展数据源支持。
527 0
Flink CDC 在阿里云实时计算Flink版的云上实践
|
9月前
|
存储 关系型数据库 BI
实时计算UniFlow:Flink+Paimon构建流批一体实时湖仓
实时计算架构中,传统湖仓架构在数据流量管控和应用场景支持上表现良好,但在实际运营中常忽略细节,导致新问题。为解决这些问题,提出了流批一体的实时计算湖仓架构——UniFlow。该架构通过统一的流批计算引擎、存储格式(如Paimon)和Flink CDC工具,简化开发流程,降低成本,并确保数据一致性和实时性。UniFlow还引入了Flink Materialized Table,实现了声明式ETL,优化了调度和执行模式,使用户能灵活调整新鲜度与成本。最终,UniFlow不仅提高了开发和运维效率,还提供了更实时的数据支持,满足业务决策需求。
|
人工智能 Apache 流计算
Flink Forward Asia 2024 上海站|探索实时计算新边界
Flink Forward Asia 2024 即将盛大开幕!11 月 29 至 30 日在上海举行,大会聚焦 Apache Flink 技术演进与未来规划,涵盖流式湖仓、流批一体、Data+AI 融合等前沿话题,提供近百场专业演讲。立即报名,共襄盛举!官网:https://asia.flink-forward.org/shanghai-2024/
1190 33
Flink Forward Asia 2024 上海站|探索实时计算新边界
|
10月前
|
SQL 运维 数据可视化
阿里云实时计算Flink版产品体验测评
阿里云实时计算Flink基于Apache Flink构建,提供一站式实时大数据分析平台,支持端到端亚秒级实时数据分析,适用于实时大屏、实时报表、实时ETL和风控监测等场景,具备高性价比、开发效率、运维管理和企业安全等优势。

热门文章

最新文章