Flink 自定义触发器实现带超时时间的 CountWindow

点击上方蓝色字体,选择“设为星标

回复”资源“获取更多资源

Flink 的 window 有两个基本款,TimeWindow 和 CountWindow。
TimeWindow 是到时间就触发窗口,CountWindow 是到数量就触发。

如果我需要到时间就触发,并且到时间之前如果已经积累了足够数量的数据;或者在限定时间内没有积累足够数量的数据,我依然希望触发窗口业务,那么就需要自定义触发器。

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.typeutils.base.LongSerializer;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.windowing.triggers.Trigger;
import org.apache.flink.streaming.api.windowing.triggers.TriggerResult;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 带超时的计数窗口触发器
 */
public class CountTriggerWithTimeout<T> extends Trigger<T, TimeWindow> {
    private static Logger LOG = LoggerFactory.getLogger(CountTriggerWithTimeout.class);


    /**
     * 窗口最大数据量
     */
    private int maxCount;
    /**
     * event time / process time
     */
    private TimeCharacteristic timeType;
    /**
     * 用于储存窗口当前数据量的状态对象
     */
    private ReducingStateDescriptor<Long> countStateDescriptor =
            new ReducingStateDescriptor("counter", new Sum(), LongSerializer.INSTANCE);




    public CountTriggerWithTimeout(int maxCount, TimeCharacteristic timeType) {


        this.maxCount = maxCount;
        this.timeType = timeType;
    }




    private TriggerResult fireAndPurge(TimeWindow window, TriggerContext ctx) throws Exception {
        clear(window, ctx);
        return TriggerResult.FIRE_AND_PURGE;
    }




    @Override
    public TriggerResult onElement(T element, long timestamp, TimeWindow window, TriggerContext ctx) throws Exception {
        ReducingState<Long> countState = ctx.getPartitionedState(countStateDescriptor);
        countState.add(1L);


        if (countState.get() >= maxCount) {
            LOG.info("fire with count: " + countState.get());
            return fireAndPurge(window, ctx);
        }
        if (timestamp >= window.getEnd()) {
            LOG.info("fire with tiem: " + timestamp);
            return fireAndPurge(window, ctx);
        } else {
            return TriggerResult.CONTINUE;
        }
    }


    @Override
    public TriggerResult onProcessingTime(long time, TimeWindow window, TriggerContext ctx) throws Exception {
        if (timeType != TimeCharacteristic.ProcessingTime) {
            return TriggerResult.CONTINUE;
        }


        if (time >= window.getEnd()) {
            return TriggerResult.CONTINUE;
        } else {
            LOG.info("fire with process tiem: " + time);
            return fireAndPurge(window, ctx);
        }
    }


    @Override
    public TriggerResult onEventTime(long time, TimeWindow window, TriggerContext ctx) throws Exception {
        if (timeType != TimeCharacteristic.EventTime) {
            return TriggerResult.CONTINUE;
        }


        if (time >= window.getEnd()) {
            return TriggerResult.CONTINUE;
        } else {
            LOG.info("fire with event tiem: " + time);
            return fireAndPurge(window, ctx);
        }
    }


    @Override
    public void clear(TimeWindow window, TriggerContext ctx) throws Exception {
        ReducingState<Long> countState = ctx.getPartitionedState(countStateDescriptor);
        countState.clear();
    }


    /**
     * 计数方法
     */
    class Sum implements ReduceFunction<Long> {


        @Override
        public Long reduce(Long value1, Long value2) throws Exception {
            return value1 + value2;
        }
    }
}

使用示例(超时时间 10 秒,数据量上限 1000):

stream
        .timeWindowAll(Time.seconds(10))
        .trigger(
                new CountTriggerWithTimeout(1000, TimeCharacteristic.ProcessingTime)
        )
        .process(new XxxxWindowProcessFunction())
        .addSink(new XxxSinkFunction())
        .name("Xxx");

即可。

欢迎点赞+收藏+转发朋友圈素质三连

文章不错?点个【在看】吧! ????

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: Apache Flink支持通过实现ReduceFunction和GroupReduceFunction接口来实现定义的collect_set函数。下面是一个示例Java代码:public class CollectSetReducer implements ReduceFunction<String> { public String reduce(String value1, String value2) throws Exception { Set<String> set = new HashSet<String>(); set.add(value1); set.add(value2); return set.stream().collect(Collectors.joining(",")); } } ### 回答2: Apache Flink是一个流处理和批处理框架,它提供了丰富的内置操作符和函数来处理流式和批处理数据。然而,Apache Flink没有提供内置的collect_set函数,用于将数据流中的元素收集到一个集合中。 要在Apache Flink中自定义实现collect_set函数,您可以使用Flink提供的ReduceFunction和RichFlatMapFunction接口来实现。下面是一个示例的Java代码实现: 首先,我们需要自定义一个ReduceFunction实现,用于将相同key的元素合并到一个集合中: ```java public class CollectSetReduceFunction<T> implements ReduceFunction<T> { @Override public T reduce(T value1, T value2) throws Exception { // 将value2合并到value1中 // 这里假设value1和value2是集合类型 if (value1 instanceof Set) { ((Set) value1).addAll((Set) value2); return value1; } return null; } } ``` 接下来,我们需要自定义一个RichFlatMapFunction实现,用于将每个元素发送到下游操作符,并将其添加到collect_set的集合中: ```java public class CollectSetFunction<T> extends RichFlatMapFunction<T, Set<T>> { private Set<T> resultSet; @Override public void open(Configuration parameters) throws Exception { super.open(parameters); resultSet = new HashSet<>(); } @Override public void flatMap(T value, Collector<Set<T>> out) throws Exception { resultSet.add(value); } @Override public void close() throws Exception { super.close(); out.collect(resultSet); } } ``` 最后,您可以在Flink的数据流中使用自定义的collect_set函数,例如: ```java DataStream<Tuple2<String, Integer>> dataStream = ... // 输入数据流 DataStream<Set<Integer>> resultStream = dataStream .groupBy(0) // 按key分组 .reduce(new CollectSetReduceFunction<>()) // 自定义reduce函数 .flatMap(new CollectSetFunction<>()); // 自定义flatMap函数 resultStream.print(); // 输出结果 ``` 以上是一个简单的示例,用于演示如何在Apache Flink中自定义实现collect_set函数。根据您的具体需求,您可能需要根据数据类型和业务逻辑进行一些修改和调整。 ### 回答3: Apache Flink是一个开源的流处理框架,它提供了各种数据操作和处理功能。如果想要实现类似于collect_set的功能,可以使用Flink的自定义函数来完成。 在Java中,我们可以创建一个自定义的聚合函数,来实现collect_set的功能。聚合函数可以让我们对输入的数据进行逐条处理,并输出最终的聚合结果。 以下是一个使用Java代码实现collect_set功能的示例: ```java import org.apache.flink.api.common.functions.AggregateFunction; import java.util.HashSet; import java.util.Set; public class CollectSetFunction<T> implements AggregateFunction<T, Set<T>, Set<T>> { @Override public Set<T> createAccumulator() { return new HashSet<>(); } @Override public Set<T> add(T value, Set<T> accumulator) { accumulator.add(value); return accumulator; } @Override public Set<T> getResult(Set<T> accumulator) { return accumulator; } @Override public Set<T> merge(Set<T> a, Set<T> b) { a.addAll(b); return a; } } ``` 在这个示例中,我们实现了`AggregateFunction`接口,并重写了其中的四个方法来完成collect_set的功能。 `createAccumulator()`方法用于创建一个空的累加器,这里我们使用HashSet来存储结果集。 `add()`方法会在每个输入数据上被调用,它将每个输入元素添加到累加器中。 `getResult()`方法在处理完所有元素后返回最终的结果。 `merge()`方法用于合并多个并行计算的累加器。 通过将这个自定义聚合函数应用到Flink的数据流中,我们就可以实现类似于collect_set的功能,将相同的元素放入一个集合中。 ```java DataStream<Tuple2<String, Integer>> input = ...; // 输入数据流 DataStream<Tuple2<String, Set<Integer>>> result = input .keyBy(0) .aggregate(new CollectSetFunction<>()); ``` 在这个示例中,我们先将输入数据流按照某个键值进行分组(这里使用第一个字段作为键),然后应用我们自定义的聚合函数`CollectSetFunction`。 最终的结果数据流`result`将包含分组后的数据及其对应的集合。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值