This repository has been archived by the owner on Apr 8, 2024. It is now read-only.
forked from elodina/go_kafka_client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducer.go
279 lines (241 loc) · 8.08 KB
/
producer.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package go_kafka_client
import (
"bytes"
"encoding/binary"
"errors"
hashing "hash"
"hash/fnv"
"math/rand"
"time"
)
type Producer interface {
Errors() <-chan *FailedMessage
Successes() <-chan *ProducerMessage
Input() chan <- *ProducerMessage
Close() error
AsyncClose()
}
type ProducerConstructor func(config *ProducerConfig) Producer
type ProducerMessage struct {
Topic string
Key interface{}
Value interface{}
KeyEncoder Encoder
ValueEncoder Encoder
offset int64
partition int32
}
type Partitioner interface {
Partition(key []byte, numPartitions int32) (int32, error)
RequiresConsistency() bool
}
type PartitionerConstructor func() Partitioner
type ProducerConfig struct {
Clientid string
BrokerList []string
SendBufferSize int
CompressionCodec string
FlushByteCount int
FlushTimeout time.Duration
BatchSize int
MaxMessageBytes int
MaxMessagesPerRequest int
Acks int
RetryBackoff time.Duration
Timeout time.Duration
Partitioner PartitionerConstructor
KeyEncoder Encoder
ValueEncoder Encoder
AckSuccesses bool
//Retries int //TODO ??
}
func DefaultProducerConfig() *ProducerConfig {
return &ProducerConfig{
Clientid: "mirrormaker",
MaxMessageBytes: 1000000,
Acks: 1,
RetryBackoff: 250 * time.Millisecond,
KeyEncoder: &ByteEncoder{},
ValueEncoder: &ByteEncoder{},
Partitioner: NewRandomPartitioner,
Timeout: 10 * time.Second,
BatchSize: 10,
MaxMessagesPerRequest: 100,
FlushByteCount: 65535,
FlushTimeout: 5 * time.Second,
AckSuccesses: false,
SendBufferSize: 1,
CompressionCodec: "none",
}
}
// ProducerConfigFromFile is a helper function that loads a producer's configuration information from file.
// The file accepts the following fields:
// client.id
// metadata.broker.list
// send.buffer.size
// compression.codec
// flush.byte.count
// flush.timeout
// batch.size
// max.message.bytes
// max.messages.per.request
// acks
// retry.backoff
// timeout
// The configuration file entries should be constructed in key=value syntax. A # symbol at the beginning
// of a line indicates a comment. Blank lines are ignored. The file should end with a newline character.
func ProducerConfigFromFile(filename string) (*ProducerConfig, error) {
p, err := LoadConfiguration(filename)
if err != nil {
return nil, err
}
config := DefaultProducerConfig()
setStringConfig(&config.Clientid, p["client.id"])
setStringSliceConfig(&config.BrokerList, p["metadata.broker.list"], ",")
if err := setIntConfig(&config.SendBufferSize, p["send.buffer.size"]); err != nil {
return nil, err
}
setStringConfig(&config.CompressionCodec, p["compression.codec"])
if err := setIntConfig(&config.FlushByteCount, p["flush.byte.count"]); err != nil {
return nil, err
}
if err := setDurationConfig(&config.FlushTimeout, p["flush.timeout"]); err != nil {
return nil, err
}
if err := setIntConfig(&config.BatchSize, p["batch.size"]); err != nil {
return nil, err
}
if err := setIntConfig(&config.MaxMessageBytes, p["max.message.bytes"]); err != nil {
return nil, err
}
if err := setIntConfig(&config.MaxMessagesPerRequest, p["max.messages.per.request"]); err != nil {
return nil, err
}
if err := setIntConfig(&config.Acks, p["acks"]); err != nil {
return nil, err
}
if err := setDurationConfig(&config.RetryBackoff, p["retry.backoff"]); err != nil {
return nil, err
}
if err := setDurationConfig(&config.Timeout, p["timeout"]); err != nil {
return nil, err
}
return config, nil
}
func (this *ProducerConfig) Validate() error {
if len(this.BrokerList) == 0 {
return errors.New("Broker list cannot be empty")
}
if this.Partitioner == nil {
return errors.New("Producer partitioner cannot be empty")
}
return nil
}
// Partitioner sends messages to partitions that correspond message keys
type FixedPartitioner struct {}
func NewFixedPartitioner() Partitioner {
return &FixedPartitioner{}
}
func (this *FixedPartitioner) Partition(key []byte, numPartitions int32) (int32, error) {
if key == nil {
panic("FixedPartitioner does not work without keys.")
}
partition, err := binary.ReadUvarint(bytes.NewBuffer(key))
if err != nil {
return -1, err
}
return int32(partition) % numPartitions, nil
}
func (this *FixedPartitioner) RequiresConsistency() bool {
return true
}
// RandomPartitioner implements the Partitioner interface by choosing a random partition each time.
type RandomPartitioner struct {
generator *rand.Rand
}
func NewRandomPartitioner() Partitioner {
return &RandomPartitioner{
generator: rand.New(rand.NewSource(time.Now().UTC().UnixNano())),
}
}
func (this *RandomPartitioner) Partition(key []byte, numPartitions int32) (int32, error) {
return int32(this.generator.Intn(int(numPartitions))), nil
}
func (this *RandomPartitioner) RequiresConsistency() bool {
return false
}
// RoundRobinPartitioner implements the Partitioner interface by walking through the available partitions one at a time.
type RoundRobinPartitioner struct {
partition int32
}
func NewRoundRobinPartitioner() Partitioner {
return &RoundRobinPartitioner{}
}
func (this *RoundRobinPartitioner) Partition(key []byte, numPartitions int32) (int32, error) {
if this.partition >= numPartitions {
this.partition = 0
}
ret := this.partition
this.partition++
return ret, nil
}
func (this *RoundRobinPartitioner) RequiresConsistency() bool {
return false
}
// 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 Partitioner
hasher hashing.Hash32
}
func NewHashPartitioner() Partitioner {
p := new(HashPartitioner)
p.random = NewRandomPartitioner()
p.hasher = fnv.New32a()
return p
}
func (this *HashPartitioner) Partition(key []byte, numPartitions int32) (int32, error) {
if key == nil {
return this.random.Partition(key, numPartitions)
}
this.hasher.Reset()
_, err := this.hasher.Write(key)
if err != nil {
return -1, err
}
hash := int32(this.hasher.Sum32())
if hash < 0 {
hash = -hash
}
return hash % numPartitions, nil
}
func (this *HashPartitioner) RequiresConsistency() bool {
return true
}
// 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, error) {
return p.Constant, nil
}
func (p *ConstantPartitioner) RequiresConsistency() bool {
return true
}