Skip to content

Commit 2f00b62

Browse files
committed
use semaphore to control the call to async produce
Signed-off-by: 3AceShowHand <[email protected]>
1 parent 4178837 commit 2f00b62

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

async_producer.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package sarama
22

33
import (
4+
"context"
45
"encoding/binary"
56
"errors"
67
"fmt"
8+
"golang.org/x/sync/semaphore"
79
"math"
810
"sync"
911
"time"
@@ -777,6 +779,7 @@ func (p *asyncProducer) newBrokerProducer(broker *Broker) *brokerProducer {
777779
bridge = make(chan *produceSet)
778780
pending = make(chan *brokerProducerResponse)
779781
responses = make(chan *brokerProducerResponse)
782+
weighted = semaphore.NewWeighted(int64(p.conf.Net.MaxOpenRequests))
780783
)
781784

782785
bp := &brokerProducer{
@@ -790,13 +793,14 @@ func (p *asyncProducer) newBrokerProducer(broker *Broker) *brokerProducer {
790793
}
791794
go withRecover(bp.run)
792795

796+
ctx := context.Background()
793797
// minimal bridge to make the network response `select`able
794798
go withRecover(func() {
795799
// Use a wait group to know if we still have in flight requests
796800
var wg sync.WaitGroup
797-
798801
for set := range bridge {
799802
request := set.buildRequest()
803+
_ = weighted.Acquire(ctx, 1)
800804

801805
// Count the in flight requests to know when we can close the pending channel safely
802806
wg.Add(1)
@@ -810,6 +814,7 @@ func (p *asyncProducer) newBrokerProducer(broker *Broker) *brokerProducer {
810814
res: response,
811815
}
812816
wg.Done()
817+
weighted.Release(1)
813818
}
814819
}(set)
815820

0 commit comments

Comments
 (0)