1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- package sarama
- import (
- "hash"
- "hash/fnv"
- "math/rand"
- "sync"
- "time"
- )
- type Partitioner interface {
- Partition(key Encoder, numPartitions int32) int32
- }
- type RandomPartitioner struct {
- generator *rand.Rand
- m sync.Mutex
- }
- func NewRandomPartitioner() *RandomPartitioner {
- p := new(RandomPartitioner)
- p.generator = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
- return p
- }
- func (p *RandomPartitioner) Partition(key Encoder, numPartitions int32) int32 {
- p.m.Lock()
- defer p.m.Unlock()
- return int32(p.generator.Intn(int(numPartitions)))
- }
- type RoundRobinPartitioner struct {
- partition int32
- m sync.Mutex
- }
- func (p *RoundRobinPartitioner) Partition(key Encoder, numPartitions int32) int32 {
- p.m.Lock()
- defer p.m.Unlock()
- if p.partition >= numPartitions {
- p.partition = 0
- }
- ret := p.partition
- p.partition++
- return ret
- }
- type HashPartitioner struct {
- random *RandomPartitioner
- hasher hash.Hash32
- m sync.Mutex
- }
- func NewHashPartitioner() *HashPartitioner {
- p := new(HashPartitioner)
- p.random = NewRandomPartitioner()
- p.hasher = fnv.New32a()
- return p
- }
- func (p *HashPartitioner) Partition(key Encoder, numPartitions int32) int32 {
- p.m.Lock()
- defer p.m.Unlock()
- 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()
- p.hasher.Write(bytes)
- hash := int32(p.hasher.Sum32())
- if hash < 0 {
- hash = -hash
- }
- return hash % numPartitions
- }
|