-
Notifications
You must be signed in to change notification settings - Fork 0
/
consumer.go
52 lines (43 loc) · 1.12 KB
/
consumer.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
package main
import (
"log"
"os"
"os/signal"
"sync"
"syscall"
"github.com/Shopify/sarama"
)
func main() {
consumer, err := sarama.NewConsumer([]string{"localhost:9092"}, nil)
if err != nil {
log.Fatalln("Failed to start Kafka consumer:", err)
}
defer func() {
if err := consumer.Close(); err != nil {
log.Fatalln("Failed to close Kafka consumer:", err)
}
}()
topic := "meu-topico"
partitionList, err := consumer.Partitions(topic)
if err != nil {
log.Fatalln("Failed to get partition list:", err)
}
var wg sync.WaitGroup
for _, partition := range partitionList {
pc, err := consumer.ConsumePartition(topic, partition, sarama.OffsetNewest)
if err != nil {
log.Fatalf("Failed to start consumer for partition %d: %s\n", partition, err)
}
wg.Add(1)
go func(pc sarama.PartitionConsumer) {
defer wg.Done()
for msg := range pc.Messages() {
log.Printf("Mensagem recebida: Partição: %d, Offset: %d, Valor: %s\n", msg.Partition, msg.Offset, string(msg.Value))
}
}(pc)
}
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
<-signals
wg.Wait()
}