Flink – WindowedStream

本文涉及的产品
实时计算 Flink 版,1000CU*H 3个月
简介:

Flink – WindowedStream

在WindowedStream上可以执行,如reduce,aggregate,min,max等操作

关键是要理解windowOperator对KVState的运用,因为window是用它来存储window buffer的

采用不同的KVState,会有不同的效果,如ReduceState,ListState

 

Reduce

 

复制代码
/**
     * Applies the given window function to each window. The window function is called for each
     * evaluation of the window for each key individually. The output of the window function is
     * interpreted as a regular non-windowed stream.
     *
     * <p>
     * Arriving data is incrementally aggregated using the given reducer.
     *
     * @param reduceFunction The reduce function that is used for incremental aggregation.
     * @param function The window function.
     * @param resultType Type information for the result type of the window function.
     * @param legacyWindowOpType When migrating from an older Flink version, this flag indicates
     *                           the type of the previous operator whose state we inherit.
     * @return The data stream that is the result of applying the window function to the window.
     */
    private <R> SingleOutputStreamOperator<R> reduce(
            ReduceFunction<T> reduceFunction,
            WindowFunction<T, R, K, W> function,
            TypeInformation<R> resultType,
            LegacyWindowOperatorType legacyWindowOpType) {

        String opName;
        KeySelector<T, K> keySel = input.getKeySelector();

        OneInputStreamOperator<T, R> operator;

        if (evictor != null) {
            @SuppressWarnings({"unchecked", "rawtypes"})
            TypeSerializer<StreamRecord<T>> streamRecordSerializer =
                (TypeSerializer<StreamRecord<T>>) new StreamElementSerializer(input.getType().createSerializer(getExecutionEnvironment().getConfig()));

            ListStateDescriptor<StreamRecord<T>> stateDesc = //如果有evictor,这里state是list state,需要把windows整个cache下来,这样才能去evict
                new ListStateDescriptor<>("window-contents", streamRecordSerializer);

            opName = "TriggerWindow(" + windowAssigner + ", " + stateDesc + ", " + trigger + ", " + evictor + ", " + udfName + ")"; //reduce的op name是这样拼的,可以看出window的所有相关配置

            operator =
                new EvictingWindowOperator<>(windowAssigner,
                    windowAssigner.getWindowSerializer(getExecutionEnvironment().getConfig()),
                    keySel,
                    input.getKeyType().createSerializer(getExecutionEnvironment().getConfig()),
                    stateDesc,
                    new InternalIterableWindowFunction<>(new ReduceApplyWindowFunction<>(reduceFunction, function)),
                    trigger,
                    evictor,
                    allowedLateness);

        } else { //如果没有evictor
            ReducingStateDescriptor<T> stateDesc = new ReducingStateDescriptor<>("window-contents", //这里就是ReducingState,不需要cache整个list,所以效率更高
                reduceFunction, //reduce的逻辑
                input.getType().createSerializer(getExecutionEnvironment().getConfig()));

            opName = "TriggerWindow(" + windowAssigner + ", " + stateDesc + ", " + trigger + ", " + udfName + ")";

            operator =
                new WindowOperator<>(windowAssigner,
                    windowAssigner.getWindowSerializer(getExecutionEnvironment().getConfig()),
                    keySel,
                    input.getKeyType().createSerializer(getExecutionEnvironment().getConfig()),
                    stateDesc,
                    new InternalSingleValueWindowFunction<>(function),
                    trigger,
                    allowedLateness,
                    legacyWindowOpType);
        }

        return input.transform(opName, resultType, operator);
    }
复制代码

 

reduceFunction,就是reduce的逻辑,一般只是指定这个参数

 

WindowFunction<T, R, K, W> function

TypeInformation<R> resultType

   /**
     * Applies a reduce function to the window. The window function is called for each evaluation
     * of the window for each key individually. The output of the reduce function is interpreted
     * as a regular non-windowed stream.
     */

这个function是WindowFunction,在window被fire时调用,resultType是WindowFunction的返回值,通过reduce,windowedStream会成为non-windowed stream

复制代码
   /**
     * Emits the contents of the given window using the {@link InternalWindowFunction}.
     */
    @SuppressWarnings("unchecked")
    private void emitWindowContents(W window, ACC contents) throws Exception {
        timestampedCollector.setAbsoluteTimestamp(window.maxTimestamp());
        userFunction.apply(context.key, context.window, contents, timestampedCollector);
    }
复制代码

可以看到WindowFunction是对于每个key的window都会调用一遍

复制代码
public void onEventTime(InternalTimer<K, W> timer) throws Exception {

    TriggerResult triggerResult = context.onEventTime(timer.getTimestamp());
    if (triggerResult.isFire()) {
        emitWindowContents(context.window, contents); //当window被fire的时候,调用
    }
}
复制代码

context.window是记录window的元数据,比如TimeWindow记录开始,结束时间 
contents,是windowState,包含真正的数据

 

默认不指定,给定是

PassThroughWindowFunction
复制代码
public class PassThroughWindowFunction<K, W extends Window, T> implements WindowFunction<T, T, K, W> {

    private static final long serialVersionUID = 1L;

    @Override
    public void apply(K k, W window, Iterable<T> input, Collector<T> out) throws Exception {
        for (T in: input) {
            out.collect(in);
        }
    }
}
复制代码

 

继续现在WindowOperator

复制代码
    @Override
    public void processElement(StreamRecord<IN> element) throws Exception {
    
        for (W window: elementWindows) { //对于每个被assign的window

            // drop if the window is already late
            if (isLate(window)) {
                continue;
            }

            windowState.setCurrentNamespace(window);
            windowState.add(element.getValue()); //add element的值
复制代码

 

windowState在WindowOperator.open中被初始化,

复制代码
     public void open() throws Exception {
        // create (or restore) the state that hold the actual window contents
        // NOTE - the state may be null in the case of the overriding evicting window operator
        if (windowStateDescriptor != null) {
            windowState = (InternalAppendingState<W, IN, ACC>) getOrCreateKeyedState(windowSerializer, windowStateDescriptor);
        }
复制代码

 

AbstractStreamOperator
复制代码
     protected <N, S extends State, T> S getOrCreateKeyedState(
            TypeSerializer<N> namespaceSerializer,
            StateDescriptor<S, T> stateDescriptor) throws Exception {

        if (keyedStateStore != null) {
            return keyedStateBackend.getOrCreateKeyedState(namespaceSerializer, stateDescriptor);
        }
复制代码

 

AbstractKeyedStateBackend
复制代码
     public <N, S extends State, V> S getOrCreateKeyedState(
            final TypeSerializer<N> namespaceSerializer,
            StateDescriptor<S, V> stateDescriptor) throws Exception {

        // create a new blank key/value state
        S state = stateDescriptor.bind(new StateBackend() {
            @Override
            public <T> ValueState<T> createValueState(ValueStateDescriptor<T> stateDesc) throws Exception {
                return AbstractKeyedStateBackend.this.createValueState(namespaceSerializer, stateDesc);
            }

            @Override
            public <T> ListState<T> createListState(ListStateDescriptor<T> stateDesc) throws Exception {
                return AbstractKeyedStateBackend.this.createListState(namespaceSerializer, stateDesc);
            }

            @Override
            public <T> ReducingState<T> createReducingState(ReducingStateDescriptor<T> stateDesc) throws Exception {
                return AbstractKeyedStateBackend.this.createReducingState(namespaceSerializer, stateDesc);
            }

            @Override
            public <T, ACC, R> AggregatingState<T, R> createAggregatingState(
                    AggregatingStateDescriptor<T, ACC, R> stateDesc) throws Exception {
                return AbstractKeyedStateBackend.this.createAggregatingState(namespaceSerializer, stateDesc);
            }
复制代码

可以看到这里根据不同的StateDescriptor调用bind,会生成不同的state

如果前面用的是ReducingStateDescriptor

    @Override
    public ReducingState<T> bind(StateBackend stateBackend) throws Exception {
        return stateBackend.createReducingState(this);
    }

 

所以如果用的是RockDB,

那么创建的是RocksDBReducingState

所以调用add的逻辑,

复制代码
public class RocksDBReducingState<K, N, V>
    extends AbstractRocksDBState<K, N, ReducingState<V>, ReducingStateDescriptor<V>, V>
    implements InternalReducingState<N, V> {
    @Override
    public void add(V value) throws IOException {
        try {
            writeCurrentKeyWithGroupAndNamespace();
            byte[] key = keySerializationStream.toByteArray();
            byte[] valueBytes = backend.db.get(columnFamily, key);

            DataOutputViewStreamWrapper out = new DataOutputViewStreamWrapper(keySerializationStream);
            if (valueBytes == null) {
                keySerializationStream.reset();
                valueSerializer.serialize(value, out);
                backend.db.put(columnFamily, writeOptions, key, keySerializationStream.toByteArray());
            } else {
                V oldValue = valueSerializer.deserialize(new DataInputViewStreamWrapper(new ByteArrayInputStream(valueBytes)));
                V newValue = reduceFunction.reduce(oldValue, value); //使用reduce函数合并value
                keySerializationStream.reset();
                valueSerializer.serialize(newValue, out);
                backend.db.put(columnFamily, writeOptions, key, keySerializationStream.toByteArray()); //将新的value put到backend中
            }
        } catch (Exception e) {
            throw new RuntimeException("Error while adding data to RocksDB", e);
        }
    }
复制代码

 

aggregate

这里用AggregatingStateDescriptor

并且多个参数,TypeInformation<ACC> accumulatorType,因为aggregate是不断的更新这个accumulator

复制代码
/**
     * Applies the given window function to each window. The window function is called for each
     * evaluation of the window for each key individually. The output of the window function is
     * interpreted as a regular non-windowed stream.
     *
     * <p>Arriving data is incrementally aggregated using the given aggregate function. This means
     * that the window function typically has only a single value to process when called.
     *
     * @param aggregateFunction The aggregation function that is used for incremental aggregation.
     * @param windowFunction The window function.
     * @param accumulatorType Type information for the internal accumulator type of the aggregation function
     * @param resultType Type information for the result type of the window function
     *    
     * @return The data stream that is the result of applying the window function to the window.
     * 
     * @param <ACC> The type of the AggregateFunction's accumulator
     * @param <V> The type of AggregateFunction's result, and the WindowFunction's input  
     * @param <R> The type of the elements in the resulting stream, equal to the
     *            WindowFunction's result type
     */
    public <ACC, V, R> SingleOutputStreamOperator<R> aggregate(
            AggregateFunction<T, ACC, V> aggregateFunction,
            WindowFunction<V, R, K, W> windowFunction, 
            TypeInformation<ACC> accumulatorType,
            TypeInformation<V> aggregateResultType,
            TypeInformation<R> resultType) {


        if (evictor != null) {

          //evictor仍然是用ListState
        } else {
            AggregatingStateDescriptor<T, ACC, V> stateDesc = new AggregatingStateDescriptor<>("window-contents",
                    aggregateFunction, accumulatorType.createSerializer(getExecutionEnvironment().getConfig()));

            opName = "TriggerWindow(" + windowAssigner + ", " + stateDesc + ", " + trigger + ", " + udfName + ")";

            operator = new WindowOperator<>(windowAssigner,
                    windowAssigner.getWindowSerializer(getExecutionEnvironment().getConfig()),
                    keySel,
                    input.getKeyType().createSerializer(getExecutionEnvironment().getConfig()),
                    stateDesc,
                    new InternalSingleValueWindowFunction<>(windowFunction),
                    trigger,
                    allowedLateness);
        }

        return input.transform(opName, resultType, operator);
    }
复制代码

最终用到,

RocksDBAggregatingState
复制代码
    @Override
    public R get() throws IOException {
        try {
            // prepare the current key and namespace for RocksDB lookup
            writeCurrentKeyWithGroupAndNamespace();
            final byte[] key = keySerializationStream.toByteArray();

            // get the current value
            final byte[] valueBytes = backend.db.get(columnFamily, key);

            if (valueBytes == null) {
                return null;
            }

            ACC accumulator = valueSerializer.deserialize(new DataInputViewStreamWrapper(new ByteArrayInputStreamWithPos(valueBytes)));
            return aggFunction.getResult(accumulator); //返回accumulator的值
        }
        catch (IOException | RocksDBException e) {
            throw new IOException("Error while retrieving value from RocksDB", e);
        }
    }

    @Override
    public void add(T value) throws IOException {
        try {
            // prepare the current key and namespace for RocksDB lookup
            writeCurrentKeyWithGroupAndNamespace();
            final byte[] key = keySerializationStream.toByteArray();
            keySerializationStream.reset();

            // get the current value
            final byte[] valueBytes = backend.db.get(columnFamily, key);

            // deserialize the current accumulator, or create a blank one
            final ACC accumulator = valueBytes == null ? //create new或从state中反序列化出来
                    aggFunction.createAccumulator() :
                    valueSerializer.deserialize(new DataInputViewStreamWrapper(new ByteArrayInputStreamWithPos(valueBytes)));

            // aggregate the value into the accumulator
            aggFunction.add(value, accumulator); //更新accumulator

            // serialize the new accumulator
            final DataOutputViewStreamWrapper out = new DataOutputViewStreamWrapper(keySerializationStream);
            valueSerializer.serialize(accumulator, out);

            // write the new value to RocksDB
            backend.db.put(columnFamily, writeOptions, key, keySerializationStream.toByteArray());
        }
        catch (IOException | RocksDBException e) {
            throw new IOException("Error while adding value to RocksDB", e);
        }
    }
复制代码

 

给个aggFunction的例子,

复制代码
    private static class AddingFunction implements AggregateFunction<Long, MutableLong, Long> {

        @Override
        public MutableLong createAccumulator() {
            return new MutableLong();
        }

        @Override
        public void add(Long value, MutableLong accumulator) {
            accumulator.value += value;
        }

        @Override
        public Long getResult(MutableLong accumulator) {
            return accumulator.value;
        }

        @Override
        public MutableLong merge(MutableLong a, MutableLong b) {
            a.value += b.value;
            return a;
        }
    }

    private static final class MutableLong {
        long value;
    }
复制代码

aggregate和reduce比,更通用,

reduce, A1 reduce A2 = A3

aggregate,a1 a2… aggregate = b

 

apply

更通用,就是不会再cache的时候做预算,而是需要cache整个windows数据,在触发的时候再apply

复制代码
   /**
     * Applies the given window function to each window. The window function is called for each
     * evaluation of the window for each key individually. The output of the window function is
     * interpreted as a regular non-windowed stream.
     *
     * <p>
     * Note that this function requires that all data in the windows is buffered until the window
     * is evaluated, as the function provides no means of incremental aggregation.
     *
     * @param function The window function.
     * @param resultType Type information for the result type of the window function
     * @return The data stream that is the result of applying the window function to the window.
     */
    public <R> SingleOutputStreamOperator<R> apply(WindowFunction<T, R, K, W> function, TypeInformation<R> resultType) {

        if (evictor != null) {
            //
        } else {
            ListStateDescriptor<T> stateDesc = new ListStateDescriptor<>("window-contents", //因为要cache所有数据,所以一定是ListState
                input.getType().createSerializer(getExecutionEnvironment().getConfig()));

            opName = "TriggerWindow(" + windowAssigner + ", " + stateDesc + ", " + trigger + ", " + udfName + ")";

            operator =
                new WindowOperator<>(windowAssigner,
                    windowAssigner.getWindowSerializer(getExecutionEnvironment().getConfig()),
                    keySel,
                    input.getKeyType().createSerializer(getExecutionEnvironment().getConfig()),
                    stateDesc,
                    new InternalIterableWindowFunction<>(function),
                    trigger,
                    allowedLateness,
                    legacyWindowOpType);
        }

        return input.transform(opName, resultType, operator);
    }
复制代码

这里就很简单了,你必须要给出WindowFunction,用于处理window触发时的结果

这里也需要指明resultType

而且使用ListStateDescriptor,这种state只是把element加到list中

 

 

AggregationFunction

如sum,min,max

复制代码
   /**
     * Applies an aggregation that sums every window of the data stream at the
     * given position.
     *
     * @param positionToSum The position in the tuple/array to sum
     * @return The transformed DataStream.
     */
    public SingleOutputStreamOperator<T> sum(int positionToSum) {
        return aggregate(new SumAggregator<>(positionToSum, input.getType(), input.getExecutionConfig()));
    }
复制代码

 

public class SumAggregator<T> extends AggregationFunction<T> {

 

复制代码
public abstract class AggregationFunction<T> implements ReduceFunction<T> {
    private static final long serialVersionUID = 1L;

    public enum AggregationType {
        SUM, MIN, MAX, MINBY, MAXBY,
    }

}
复制代码

可以看到,无法顾名思义,这些AggregationFunction,是用reduce实现的

相关实践学习
基于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日以线上峰会的形式与大家见面。
相关文章
|
Windows 流计算 存储
|
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 上海站|探索实时计算新边界

热门文章

最新文章