partitioner.go 980 B

1234567891011121314151617181920212223242526272829303132
  1. package sarama
  2. import "math/rand"
  3. // Partitioner is anything that, given a Kafka message key and a number of partitions indexed [0...numPartitions-1],
  4. // decides to which partition to send the message. RandomPartitioner and RoundRobinPartitioner are the
  5. // two simple default implementations.
  6. type Partitioner interface {
  7. Partition(key Encoder, numPartitions int) int
  8. }
  9. // RandomPartitioner implements the Partitioner interface by choosing a random partition each time.
  10. type RandomPartitioner struct {
  11. }
  12. func (p RandomPartitioner) Partition(key Encoder, numPartitions int) int {
  13. return rand.Intn(numPartitions)
  14. }
  15. // RoundRobinPartitioner implements the Partitioner interface by walking through the available partitions one at a time.
  16. type RoundRobinPartitioner struct {
  17. partition int
  18. }
  19. func (p *RoundRobinPartitioner) Partition(key Encoder, numPartitions int) int {
  20. if p.partition >= numPartitions {
  21. p.partition = 0
  22. }
  23. ret := p.partition
  24. p.partition++
  25. return ret
  26. }