[英]how to process data in chunks/batches with kafka streams?
对于大数据中的许多情况,最好一次处理一小块记录缓冲区,而不是一次处理一条记录。
自然的例子是调用一些支持批处理以提高效率的外部 API。
我们如何在 Kafka Streams 中做到这一点? 我在 API 中找不到任何看起来像我想要的东西。
到目前为止,我有:
builder.stream[String, String]("my-input-topic")
.mapValues(externalApiCall).to("my-output-topic")
我想要的是:
builder.stream[String, String]("my-input-topic")
.batched(chunkSize = 2000).map(externalBatchedApiCall).to("my-output-topic")
在 Scala 和 Akka Streams 中,该函数称为grouped
或batch
。 在 Spark Structured Streaming 中,我们可以执行mapPartitions.map(_.grouped(2000).map(externalBatchedApiCall))
。
似乎还不存在。 观看此空间https://issues.apache.org/jira/browse/KAFKA-7432
你可以使用队列。 像下面这样的东西,
@Component
@Slf4j
public class NormalTopic1StreamProcessor extends AbstractStreamProcessor<String> {
public NormalTopic1StreamProcessor(KafkaStreamsConfiguration configuration) {
super(configuration);
}
@Override
Topology buildTopology() {
KStream<String, String> kStream = streamsBuilder.stream("normalTopic", Consumed.with(Serdes.String(), Serdes.String()));
// .peek((key, value) -> log.info("message received by stream 0"));
kStream.process(() -> new AbstractProcessor<String, String>() {
final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(100);
final List<String> collection = new ArrayList<>();
@Override
public void init(ProcessorContext context) {
super.init(context);
context.schedule(Duration.of(1, ChronoUnit.MINUTES), WALL_CLOCK_TIME, timestamp -> {
processQueue();
context().commit();
});
}
@Override
public void process(String key, String value) {
queue.add(value);
if (queue.remainingCapacity() == 0) {
processQueue();
}
}
public void processQueue() {
queue.drainTo(collection);
long count = collection.stream().peek(System.out::println).count();
if (count > 0) {
System.out.println("count is " + count);
collection.clear();
}
}
});
kStream.to("normalTopic1");
return streamsBuilder.build();
}
}
我怀疑,如果 Kafka 流目前像其他工具一样支持固定大小的窗口。
但是有基于时间的窗口,由 kafka 流支持。 https://kafka.apache.org/11/documentation/streams/developer-guide/dsl-api.html#windowing
您可以随时间定义窗口大小,而不是记录数。
在您的情况下,可以选择使用 Tumbling Time Window。 这些是不重叠的、固定大小的时间窗口。
例如,大小为 5000 毫秒的滚动窗口具有可预测的窗口边界 [0;5000),[5000;10000),... - 而不是 [1000;6000),[6000;11000),...甚至某些东西“随机”如 [1452;6452),[6452;11452),....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.