This repository has been archived by the owner on Dec 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
consumer.go
78 lines (63 loc) · 1.51 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
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
package tailtopic
import (
"fmt"
"os"
"sync"
"github.com/Shopify/sarama"
)
type consumer interface {
consume(messages chan message, closing chan bool) error
}
type kafkaConsumer struct {
topic string
offset string
broker string
decoder decoder
}
func (kc *kafkaConsumer) offsetVal() int64 {
switch kc.offset {
case "earliest":
return sarama.OffsetOldest
default:
return sarama.OffsetNewest
}
}
func (kc *kafkaConsumer) consume(messages chan message, closing chan bool) error {
var wg sync.WaitGroup
consumer, err := sarama.NewConsumer([]string{kc.broker}, nil)
if err != nil {
return err
}
partitionList, err := consumer.Partitions(kc.topic)
if err != nil {
return err
}
for _, partition := range partitionList {
partitionConsumer, err := consumer.ConsumePartition(kc.topic, partition, kc.offsetVal())
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to start partition consumer: %s\n", err)
continue
}
go func(pc sarama.PartitionConsumer) {
<-closing
pc.AsyncClose()
}(partitionConsumer)
wg.Add(1)
go func(pc sarama.PartitionConsumer) {
defer wg.Done()
for msg := range pc.Messages() {
val, err := kc.decoder.decode(msg.Value)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to decode message %s. Error: %v\n", string(msg.Value), err)
}
messages <- message{value: val}
}
}(partitionConsumer)
}
wg.Wait()
close(messages)
if err := consumer.Close(); err != nil {
fmt.Fprintf(os.Stderr, "Failed to close consumer: %s\n", err)
}
return nil
}