-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathsarama_async_producer_goroutines.go
62 lines (53 loc) · 1.11 KB
/
sarama_async_producer_goroutines.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
package main
import (
"github.com/Shopify/sarama"
"log"
"os"
"os/signal"
"sync"
"time"
)
var (
wg sync.WaitGroup
enqueued, successes, errors int
)
func main() {
config := sarama.NewConfig()
config.Producer.Return.Successes = false
producer, err := sarama.NewAsyncProducer([]string{"localhost:9092"}, config)
if err != nil {
panic(err)
}
// Trap SIGINT to trigger a graceful shutdown.
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
ProducerLoop:
for {
message := &sarama.ProducerMessage{Topic: "test13", Value: sarama.StringEncoder("testing 123")}
select {
case producer.Input() <- message:
time.Sleep(time.Second)
enqueued++
case <-signals:
producer.AsyncClose() // Trigger a shutdown of the producer.
break ProducerLoop
}
}
wg.Add(1)
go func() {
defer wg.Done()
for range producer.Successes() {
successes++
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for err := range producer.Errors() {
log.Println(err)
errors++
}
}()
wg.Wait()
log.Printf("Successfully produced: %d; errors: %d\n", successes, errors)
}