Samza在发送消息时会自动创建分区吗



如果您使用Samza的OutgoingMessageEnvelope以以下格式发送消息:

public OutgoingMessageEnvelope(SystemStream systemStream,
                               java.lang.Object partitionKey,
                               java.lang.Object key,
                               java.lang.Object message)
Constructs a new OutgoingMessageEnvelope from specified components.
Parameters:
systemStream - Object representing the appropriate stream of which this envelope will be sent on.
partitionKey - A key representing which partition of the systemStream to send this envelope on.
key - A deserialized key to be used for the message.
message - A deserialized message to be sent in this envelope.

如果您在流任务的process()方法中调用此方法,并希望将传入的消息路由到适当的分区,Samza会在您调用该方法时为您创建分区吗?

例如

MessageA = {"id": "idA", "key": "keyA", "body":"some details"}
MessageB = {"id": "idB", "key": "keyB", "body":"some more details"}

如果我在流任务的process()中调用,其中msg是消息实例:

public void process(IncomingMessageEnvelope envelope, MessageCollector collector, TaskCoordinator coordinator) {
    // ...
    String partition = msg["id"]
    String key = msg["key"]
    collector.send(new OutgoingMessageEnvelope(new SystemStream("kafka", "PartitionedMessages"), id, key, msg));
    // ...

这会自动为我创建分区idA和idB吗(即,在我向它们发送消息之前,我需要创建这些分区吗)?我希望能够将消息路由到适当的分区,并能够使用单独的消息键记录压缩。

创建主题时必须指定分区数。您不能动态添加新分区(好吧,可以,但这并不容易,Samza也不会自动添加)。如果主题不存在但具有默认分区数,Samza应该为您创建新的主题。这取决于设置。你可以测试一下。

但是值msg["id"]并没有指定分区的名称。这个值只是用来计算目标分区的数量。该值被散列为一个数字,然后使用模进行修剪。类似这样的东西(有更多的算法,这是基本的算法):

partitionID = hash(msg["id"]) % total_number_of_partitions

并且partitionID总是一个非负整数。这意味着实际上有多少分区并不重要。它总是在某些地方结束。其主要思想是,如果您有两个具有相同msg["id"]的消息,那么这些消息将最终位于相同的分区中。这通常是你想要的。

日志压缩将如您所期望的那样工作——它将从特定分区中删除具有相同密钥的消息(但如果您有两个具有相同密钥、具有两个不同分区的消息,则不会删除它们)。

仅供参考,你可以使用kafkacat来找出分区的数量和其他有用的东西。

最新更新