forked from IBM/sarama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpartitioner.go
95 lines (83 loc) · 2.52 KB
/
partitioner.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package sarama
import (
"hash"
"hash/fnv"
"math/rand"
"sync"
"time"
)
// Partitioner is anything that, given a Kafka message key and a number of partitions indexed [0...numPartitions-1],
// decides to which partition to send the message. RandomPartitioner, RoundRobinPartitioner and HashPartitioner are provided
// as simple default implementations.
type Partitioner interface {
Partition(key Encoder, numPartitions int32) int32
}
// RandomPartitioner implements the Partitioner interface by choosing a random partition each time.
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)))
}
// RoundRobinPartitioner implements the Partitioner interface by walking through the available partitions one at a time.
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
}
// HashPartitioner implements the Partitioner interface. If the key is nil, or fails to encode, then a random partition
// is chosen. Otherwise the FNV-1a hash of the encoded bytes is used modulus the number of partitions. This ensures that messages
// with the same key always end up on the same partition.
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
}
// ConstantPartitioner implements the Partitioner interface by just returning a constant value.
type ConstantPartitioner struct {
Constant int32
}
func (p *ConstantPartitioner) Partition(key Encoder, numPartitions int32) int32 {
return p.Constant
}