kafka中消息key作用与分区规则关系

在 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 运算。

整理的流程图
kafka生产者消息分区规则

https://www.volcengine.com/theme/746069-K-7-1

https://zhuanlan.zhihu.com/p/485957664

相关推荐
Lansonli1 小时前
大数据Spark(九十五):Spark Shuffle 参数调优全解析
大数据·分布式·spark
Nefu_lyh17 小时前
【Spark】05Spark 数据读取与保存:文件格式、文件系统与结构化数据
大数据·分布式·spark
云边有个稻草人21 小时前
集中式与分布式怎么选?谈谈金仓数据库的架构取舍
分布式·国产数据库·架构选型·金仓数据库·集中式数据库·企业级数据库·核心业务系统
东风微鸣1 天前
QuePaxa VS Raft:广域网共识,为什么「慢但不停」胜过「快但一抖就死」
分布式·云原生·raft
wdf80881 天前
面向大规模科学数据可视化的ParaView分布式架构优化与UltraLAB高性能计算平台适配研究
分布式·信息可视化·架构·paraview
崖边看雾1 天前
Kafka 手册
分布式·面试·kafka
starzy19902 天前
Structured Streaming Kafka Sink:写出一条生产级的回流链路
大数据·分布式·spark·kafka
国科安芯2 天前
编队不是多放几颗星:分布式雷达与编队飞行任务中星内协同网络的确定性时序
网络·分布式·fpga开发·架构·低轨卫星·抗辐射
AllData公司负责人3 天前
实战一:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 File 到 Doris 高效数据同步链路,批量文件离线入仓
数据库·人工智能·分布式·大模型·数据传输·数据同步·连接器
starzy19903 天前
Structured Streaming 集成 Kafka 实现:读写路径、位点语义与生产调优
大数据·分布式·spark·kafka