[英]CompletableFutures: processing of CompletableFuture chains in parallel
[英]Can we do parallel Kafka Streams processing with CompletableFutures
是否可以使用 Java CompletableFutures 在 Kafka stream 应用程序中进行并行工作?
我想从 1 个 Kafka 主题中读取,创建两个窗口计数,1 分钟,另一个小时,但并行执行。
我写了一些示例代码。 我能够让它工作,但查看 Kafka stream 文档,因为 KafkaStreams 为每个分区分配 1 个任务,并且它不能 go 超出单线程我不确定这段代码是否会产生预期的效果。
CompletableFuture completableFutureOfMinute = CompletableFuture.runAsync(() -> {
inputStream.groupByKey()
.windowedBy(TimeWindows.of(Duration.ofMinutes(1)).grace(Duration.ofMinutes(1)))
.count(Materialized.<String, Long, WindowStore<Bytes, byte[]>>as(
"minute-store")
.withRetention(Duration.ofMinutes(1)))
.toStream()
.to("result-topic");
});
CompletableFuture completableFutureOfHour = CompletableFuture.runAsync(() -> {
inputStream.groupByKey()
.windowedBy(TimeWindows.of(Duration.ofHours(1)).grace(Duration.ofHours(1)))
.count(Materialized.<String, Long, WindowStore<Bytes, byte[]>>as(
"hour-store")
.withRetention(Duration.ofHours(1)))
.toStream()
.to("result-topic-2", produced);
});
final CompletableFuture<Void> combinedFutures = CompletableFuture.allOf(completableFutureOfMinute,
completableFutureOfHour);
try {
combinedFutures.get();
} catch (final Exception ex) {
}
您的程序似乎不正确。
请注意,使用 DSL,您基本上组装了一个数据流程序,并且数据处理仅在您调用KafkaStreams#start()
时开始。 因此,在指定处理逻辑的同时使用Futures
并没有帮助,因为尚未处理任何数据。
Kafka Streams 基于任务并行化。 因此,如果您想同时处理 windows ,则需要“复制”输入主题以将程序(称为Topology
)拆分为独立的部分(称为SubTopology
):
KStream input = builder.stream(...);
input.groupByKey().windowBy(/* 1 min */).count(...);
input.repartition().groupByKey().windowBy(/* 1 hour */).count();
使用repartition()
您的程序将被拆分为两个子拓扑,并且您将获得每个子拓扑的任务,这些任务可以由不同的线程并行处理。
但是,我实际上怀疑这个程序是否会增加您的吞吐量。 如果你真的想增加你的吞吐量,你应该增加输入主题分区的数量来获得更多的并行任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.