BufferTimeSizeWeightedFlow - 数据流聚合器 - 基于时间、大小和权重

BufferTimeSizeWeightedFlow 是一个数据流聚合器,它根据时间、大小和权重将数据进行聚合。支持设置缓冲区大小限制、时间窗口和权重限制。它可以用于收集数据并以批次的形式进行处理。

主要特点:

  • 时间窗口聚合: 数据在超过指定的时间窗口后进行聚合,默认使用毫秒为单位。
  • 大小窗口聚合: 数据在达到指定的大小(数量)时进行聚合。
  • 权重聚合: 数据根据指定的权重函数进行聚合,可以控制不同数据的权重。
  • 支持空缓冲区发射: 可以配置是否发射空的缓冲区,即使没有数据也会在指定时间窗口发射。

使用示例:

import com.taobao.powermsg3.sdk.localserver.scheduler.Scheduler;
import com.taobao.powermsg3.sdk.streams.BufferTimeSizeWeightedFlow;
import com.taobao.powermsg3.sdk.util.ConstantFunction;
import io.vertx.core.Future;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;

import static com.taobao.pubsub.util.Helper.require;

/**
 * 按照时间、大小窗口聚合
 *
 * @author 虎鸣, hepin.p@alibaba-inc.com
 */
class BufferTimeSizeWeightedFlow<T> extends PmFlow<T, List<T>> {
    private final String TIMER_KEY = UUID.randomUUID().toString();
    private final ArrayList<T> EMPTY_BUFFER = new ArrayList<>(0);

    private final boolean emitEmptyBuffer;
    private final int bufferNumberLimit;

    private final long weightLimit;

    private final Function<? super T, Long> weightFunction;

    private final Duration bufferTimeInMillis;
    private long currentWeightAccumulate;

    private final BufferAccumulator<T> bufferAccumulator;

    private final Scheduler scheduler;

    public BufferTimeSizeWeightedFlow(final int bufferNumberLimit,
                                      final long bufferTimeInMillis,
                                      final Scheduler scheduler) {
        this(bufferNumberLimit, bufferTimeInMillis, false, scheduler);
    }


    public BufferTimeSizeWeightedFlow(final int bufferNumberLimit,
                                      final long bufferTimeInMillis,
                                      final boolean emitEmptyBuffer,
                                      final Scheduler scheduler) {
        this(bufferNumberLimit, Long.MAX_VALUE, ConstantFunction.ALWAYS_ZERO, bufferTimeInMillis, emitEmptyBuffer,
            new ListBufferAccumulator<>(),
            scheduler);
    }

    public BufferTimeSizeWeightedFlow(final int bufferNumberLimit,
                                      final long weightLimit,
                                      final Function<? super T, Long> weightFunction,
                                      final long bufferTimeInMillis,
                                      final boolean emitEmptyBuffer,
                                      final BufferAccumulator<T> bufferAccumulator,
                                      final Scheduler scheduler) {
        super();
        require(bufferNumberLimit > 0, 'bufferSizeLimit should > 0');
        require(bufferTimeInMillis > 1, 'bufferTime should > 1ms');
        require(weightLimit >= 0, 'weight limit must >= 0');
        require(weightFunction != null, 'weight function should not be null.');
        require(bufferAccumulator != null, 'bufferAccumulator should not be null.');
        require(scheduler != null, 'scheduler should not be null.');
        this.bufferNumberLimit = bufferNumberLimit;
        this.weightLimit = weightLimit;
        this.weightFunction = weightFunction;
        this.bufferTimeInMillis = Duration.ofMillis(bufferTimeInMillis);
        this.emitEmptyBuffer = emitEmptyBuffer;
        this.bufferAccumulator = bufferAccumulator;
        this.scheduler = scheduler;
        //schedule
        scheduleNextTickWithFixDelay();
    }

    @Override
    protected void onTimer(final Object timerKey) {
        super.onTimer(timerKey);
        if (bufferAccumulator.isNotEmpty()) {
            final List<T> result = bufferAccumulator.result();
            select(result).write(Collections.unmodifiableList(result));
            bufferAccumulator.allocate(bufferNumberLimit);
        } else if (emitEmptyBuffer) {
            select(EMPTY_BUFFER).write(Collections.unmodifiableList(EMPTY_BUFFER));
        }
    }

    @Override
    protected Future<Void> onPush(final T data) {

        final long currentElemWeight = weightFunction.apply(data);
        require(currentElemWeight >= 0, 'weight function should return >= 0');
        final long maybeWeightExceed = (currentWeightAccumulate + currentElemWeight) - weightLimit;
        if (maybeWeightExceed == 0) {
            bufferAccumulator.offer(data);
            final List<T> currentBuffer = bufferAccumulator.result();
            //reschedule
            scheduleNextTickWithFixDelay();
            bufferAccumulator.allocate(bufferNumberLimit);
            currentWeightAccumulate = 0;
            return select(currentBuffer).write(Collections.unmodifiableList(currentBuffer));
        } else if (maybeWeightExceed > 0) {
            final List<T> currentBuffer = bufferAccumulator.result();
            //reschedule
            scheduleNextTickWithFixDelay();
            bufferAccumulator.allocate(bufferNumberLimit);
            currentWeightAccumulate = 0;
            select(currentBuffer).write(Collections.unmodifiableList(currentBuffer));
        } else {
            currentWeightAccumulate += currentElemWeight;
        }

        bufferAccumulator.offer(data);
        if (bufferAccumulator.size() == bufferNumberLimit) {
            final List<T> currentBuffer = bufferAccumulator.result();
            //reschedule
            scheduleNextTickWithFixDelay();
            bufferAccumulator.allocate(bufferNumberLimit);
            currentWeightAccumulate = 0;
            return select(currentBuffer).write(Collections.unmodifiableList(currentBuffer));
        }

        return context.succeededFuture();
    }

    protected void scheduleNextTickWithFixDelay() {
        //取消之前的timer
        scheduler.cancel(TIMER_KEY);
        //重新调度一个timer
        scheduler.scheduleWithFixDelay(TIMER_KEY, bufferTimeInMillis, bufferTimeInMillis,
            () -> onTimer(TIMER_KEY),
            context);
    }

    @Override
    protected Future<Void> onUpstreamFinish() {
        scheduler.cancel(TIMER_KEY);
        if (bufferAccumulator.isNotEmpty()) {
            final List<T> currentBuffer = bufferAccumulator.result();
            return select(currentBuffer).write(Collections.unmodifiableList(currentBuffer));
        }
        return super.onUpstreamFinish();
    }
}


## 多线程并发问题分析

这段代码中,`scheduleWithFixDelay` 方法确实可能存在并发问题。在多线程高并发的情况下,可能会出现多个线程同时调用 `scheduleWithFixDelay` 方法,从而导致多个定时任务并发执行。

**解决方法:**

* **使用线程安全的定时任务框架:**  例如 Quartz、Spring Scheduled 等框架,它们提供了线程安全的定时任务调度机制。
* **将定时任务的调度放到单独的线程中:**  可以创建一个单独的线程来负责定时任务的调度,避免多个任务并发执行。

**建议:**

在高并发环境下使用 `BufferTimeSizeWeightedFlow` 时,建议使用线程安全的定时任务框架或将定时任务的调度放到单独的线程中,以确保代码的稳定性和可靠性。
``
BufferTimeSizeWeightedFlow - 数据流聚合器 - 基于时间、大小和权重

原文地址: https://www.cveoy.top/t/topic/lIff 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录