-
Notifications
You must be signed in to change notification settings - Fork 7
/
partitioner.go
70 lines (56 loc) · 1.51 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
package producer
import (
"errors"
"hash"
"hash/fnv"
"math/rand"
"time"
)
type Partitioner interface {
Partition(record *ProducerRecord, partitions []int32) (int32, error)
}
type HashPartitioner struct {
random *RandomPartitioner
hasher hash.Hash32
}
func NewHashPartitioner() *HashPartitioner {
return &HashPartitioner{
random: NewRandomPartitioner(),
hasher: fnv.New32a(),
}
}
func (hp *HashPartitioner) Partition(record *ProducerRecord, partitions []int32) (int32, error) {
if record.Key == nil {
return hp.random.Partition(record, partitions)
} else {
hp.hasher.Reset()
_, err := hp.hasher.Write(record.encodedKey)
if err != nil {
return -1, err
}
hash := int32(hp.hasher.Sum32())
if hash < 0 {
hash = -hash
}
return hash % int32(len(partitions)), nil
}
}
type RandomPartitioner struct{}
func NewRandomPartitioner() *RandomPartitioner {
rand.Seed(time.Now().UnixNano())
return new(RandomPartitioner)
}
func (rp *RandomPartitioner) Partition(record *ProducerRecord, partitions []int32) (int32, error) {
return rand.Int31n(int32(len(partitions))), nil
}
type ManualPartitioner struct{}
func NewManualPartitioner() *ManualPartitioner {
return new(ManualPartitioner)
}
func (mp *ManualPartitioner) Partition(record *ProducerRecord, partitions []int32) (int32, error) {
if record.Partition >= int32(len(partitions)) {
Logger.Warn("Invalid partition %d. Available partitions: %v", record.Partition, partitions)
return -1, errors.New("Invalid partition")
}
return record.Partition, nil
}