forked from elodina/siesta-producer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecord_accumulator.go
64 lines (55 loc) · 1.41 KB
/
record_accumulator.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
package producer
import "time"
type RecordAccumulatorConfig struct {
batchSize int
linger time.Duration
}
type RecordAccumulator struct {
input chan *ProducerRecord
config *RecordAccumulatorConfig
networkClient *NetworkClient
batchSize int
closeChan chan bool
}
func NewRecordAccumulator(config *RecordAccumulatorConfig, networkClient *NetworkClient) *RecordAccumulator {
accumulator := &RecordAccumulator{}
accumulator.input = make(chan *ProducerRecord, config.batchSize)
accumulator.config = config
accumulator.batchSize = config.batchSize
accumulator.networkClient = networkClient
accumulator.closeChan = make(chan bool)
go accumulator.sender()
return accumulator
}
func (ra *RecordAccumulator) sender() {
timeout := time.NewTimer(ra.config.linger)
batch := make([]*ProducerRecord, ra.batchSize)
batchIndex := 0
for {
select {
case <-ra.closeChan:
return
default:
select {
case message := <-ra.input:
{
batch[batchIndex] = message
batchIndex++
if batchIndex >= ra.batchSize {
ra.networkClient.send(batch[:batchIndex])
batch = make([]*ProducerRecord, ra.batchSize)
batchIndex = 0
timeout.Reset(ra.config.linger)
}
}
case <-timeout.C:
if batchIndex > 0 {
ra.networkClient.send(batch[:batchIndex])
batch = make([]*ProducerRecord, ra.batchSize)
batchIndex = 0
}
timeout.Reset(ra.config.linger)
}
}
}
}