1、配置分区
(1)随机选择分区
config.Producer.Partitioner = sarama.NewRandomPartitioner // 随机分配分区 partition
(2)轮换选择分区
config.Producer.Partitioner = sarama.NewRoundRobinPartitioner // 轮换选择分区
(3)hash选择分区
需要在消息中指定key值,可以使key值一样的消息进入相同的分区;如果未指定key值,则随机选择分区。
config.Producer.Partitioner = sarama.NewHashPartitioner // 通过设置 hash-key 自动 hash 分区,如果没有设置key,则随机选取
msg.Key = sarama.StringEncoder("topic1key") //通过设置 hash-key 自动 hash 分区
(4)指定固定分区
需要在消息中指定分区。
config.Producer.Partitioner = sarama.NewManualPartitioner // 人工指定分区
msg.Partition = 0 // 人工指定分区