在 kafka 2.0.0 的 java sdk 中
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.12</artifactId>
<version>2.0.0</version>
</dependency>
ProducerRecord 中类注释如下
A key/value pair to be sent to Kafka. This consists of a topic name to which the record is being sent, an optional partition number, and an optional key and value.
If a valid partition number is specified that partition will be used when sending the record. If no partition is specified but a key is present a partition will be chosen using a hash of the key. If neither key nor partition is present a partition will be assigned in a round-robin fashion.
The record also has an associated timestamp. If the user did not provide a timestamp, the producer will stamp the record with its current time. The timestamp eventually used by Kafka depends on the timestamp type configured for the topic.
If the topic is configured to use CreateTime, the timestamp in the producer record will be used by the broker.
If the topic is configured to use LogAppendTime, the timestamp in the producer record will be overwritten by the broker with the broker local time when it appends the message to its log.
In either of the cases above, the timestamp that has actually been used will be returned to user in RecordMetadata
说明了 key 与分区编号的关系
KafkaProducer 中会进行如下操作
partition 合法性校验
分区id大于等于集群中指定的主题的总数,抛出异常
分区计算
分区编号获取规则
如果 ProducerRecord 中 partition 字段不为空,则取对应的变量值,否则调用 Partitioner 的实现类 DefaultPartitioner 中进行分区id获取。
DefaultPartitioner 中分区id计算办法
如果 key 为 null,有两种情况
当前 topic 的可用分区数大于0
获取当前 topic 的计数器累加后的数字与可用分区数进行 mod 运算获取分区id。
当前 topic 的可用分区数小于等于0
获取当前 topic 的计数器累加后的数字与分区数进行 mod 运算获取分区id。即返回一个不可用的分区。看到这里的做法,也能理解,毕竟没有可用分区了,只能返回一个不可用分区了。
如果 key 不为 null
通过32bit的murmur2哈希算法生成一个分区编号与分区数量进行 mod 运算。
整理的流程图
https://www.volcengine.com/theme/746069-K-7-1
https://zhuanlan.zhihu.com/p/485957664