/
producer_partitioner.go
71 lines (60 loc) · 2.08 KB
/
producer_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
package kafka
import "github.com/Shopify/sarama"
// PartitionerConstructor is the type for a function capable of constructing new Partitioners.
type PartitionerConstructor func(topic string) Partitioner
type Partitioner interface {
Partition(message *ProducerFullMessage, numPartitions int32) (int32, error)
RequiresConsistency() bool
}
type wrapperPartitioner struct {
partitioner Partitioner
}
func (w *wrapperPartitioner) Partition(message *sarama.ProducerMessage, numPartitions int32) (int32, error) {
keyByte, _ := message.Key.Encode()
valueByte, _ := message.Value.Encode()
return w.partitioner.Partition(&ProducerFullMessage{
Topic: message.Topic,
Key: keyByte,
Value: valueByte,
Headers: fromSaramaRecordHeader(message.Headers),
Metadata: message.Metadata,
Offset: message.Offset,
Partition: message.Partition,
Timestamp: message.Timestamp,
}, numPartitions)
}
func (w *wrapperPartitioner) RequiresConsistency() bool {
return w.partitioner.RequiresConsistency()
}
type wrapperSaramaPartitioner struct {
partitioner sarama.Partitioner
}
func (w *wrapperSaramaPartitioner) Partition(message *ProducerFullMessage, numPartitions int32) (int32, error) {
return w.partitioner.Partition(&sarama.ProducerMessage{
Topic: message.Topic,
Key: sarama.ByteEncoder(message.Key),
Value: sarama.ByteEncoder(message.Value),
Headers: toSaramaRecordHeader(message.Headers),
Metadata: message.Metadata,
Offset: message.Offset,
Partition: message.Partition,
Timestamp: message.Timestamp,
}, numPartitions)
}
func (w *wrapperSaramaPartitioner) RequiresConsistency() bool {
return w.partitioner.RequiresConsistency()
}
func FromSaramaPartitioner(partitioner sarama.PartitionerConstructor) PartitionerConstructor {
return func(topic string) Partitioner {
return &wrapperSaramaPartitioner{
partitioner: partitioner(topic),
}
}
}
func toSaramaPartitioner(partitioner PartitionerConstructor) sarama.PartitionerConstructor {
return func(topic string) sarama.Partitioner {
return &wrapperPartitioner{
partitioner: partitioner(topic),
}
}
}