By default, Sarama uses the message's key to consistently assign a partition to a message using hashing. If no key is set, a random partition will be chosen. This example shows how you can partition messages randomly, even when a key is set, by overriding Config.Producer.Partitioner.
()
| 431 | // This example shows how you can partition messages randomly, even when a key is set, |
| 432 | // by overriding Config.Producer.Partitioner. |
| 433 | func ExamplePartitioner_random() { |
| 434 | config := NewTestConfig() |
| 435 | config.Producer.Partitioner = NewRandomPartitioner |
| 436 | |
| 437 | producer, err := NewSyncProducer([]string{"localhost:9092"}, config) |
| 438 | if err != nil { |
| 439 | log.Println(err) |
| 440 | return |
| 441 | } |
| 442 | defer func() { |
| 443 | if err := producer.Close(); err != nil { |
| 444 | log.Println("Failed to close producer:", err) |
| 445 | } |
| 446 | }() |
| 447 | |
| 448 | msg := &ProducerMessage{Topic: "test", Key: StringEncoder("key is set"), Value: StringEncoder("test")} |
| 449 | partition, offset, err := producer.SendMessage(msg) |
| 450 | if err != nil { |
| 451 | log.Println("Failed to produce message to kafka cluster.") |
| 452 | return |
| 453 | } |
| 454 | |
| 455 | log.Printf("Produced message to partition %d with offset %d", partition, offset) |
| 456 | } |
| 457 | |
| 458 | // This example shows how to assign partitions to your messages manually. |
| 459 | func ExamplePartitioner_manual() { |
nothing calls this directly
no test coverage detected