1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- package sarama
- import (
- "hash"
- "hash/fnv"
- "math/rand"
- "time"
- )
- type Partitioner interface {
- Partition(key Encoder, numPartitions int32) int32
- }
- type PartitionerConstructor func() Partitioner
- type RandomPartitioner struct {
- generator *rand.Rand
- }
- func NewRandomPartitioner() Partitioner {
- p := new(RandomPartitioner)
- p.generator = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
- return p
- }
- func (p *RandomPartitioner) Partition(key Encoder, numPartitions int32) int32 {
- return int32(p.generator.Intn(int(numPartitions)))
- }
- type RoundRobinPartitioner struct {
- partition int32
- }
- func NewRoundRobinPartitioner() Partitioner {
- return &RoundRobinPartitioner{}
- }
- func (p *RoundRobinPartitioner) Partition(key Encoder, numPartitions int32) int32 {
- if p.partition >= numPartitions {
- p.partition = 0
- }
- ret := p.partition
- p.partition++
- return ret
- }
- type HashPartitioner struct {
- random Partitioner
- hasher hash.Hash32
- }
- func NewHashPartitioner() Partitioner {
- p := new(HashPartitioner)
- p.random = NewRandomPartitioner()
- p.hasher = fnv.New32a()
- return p
- }
- func (p *HashPartitioner) Partition(key Encoder, numPartitions int32) int32 {
- if key == nil {
- return p.random.Partition(key, numPartitions)
- }
- bytes, err := key.Encode()
- if err != nil {
- return p.random.Partition(key, numPartitions)
- }
- p.hasher.Reset()
- _, err = p.hasher.Write(bytes)
- if err != nil {
- return p.random.Partition(key, numPartitions)
- }
- hash := int32(p.hasher.Sum32())
- if hash < 0 {
- hash = -hash
- }
- return hash % numPartitions
- }
- type ConstantPartitioner struct {
- Constant int32
- }
- func (p *ConstantPartitioner) Partition(key Encoder, numPartitions int32) int32 {
- return p.Constant
- }
|