forked from open-telemetry/opentelemetry-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsumer.go
88 lines (72 loc) · 2.1 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
79
80
81
82
83
84
85
86
87
88
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package kafka
import (
"context"
pb "github.com/open-telemetry/opentelemetry-demo/src/accountingservice/genproto/oteldemo"
"github.com/IBM/sarama"
"github.com/sirupsen/logrus"
"github.com/uptrace/opentelemetry-go-extra/otellogrus"
"google.golang.org/protobuf/proto"
)
var (
Topic = "orders"
ProtocolVersion = sarama.V3_0_0_0
GroupID = "accountingservice"
)
func initLogger() {
logrus.AddHook(otellogrus.NewHook(otellogrus.WithLevels(
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
logrus.WarnLevel,
)))
}
func StartConsumerGroup(ctx context.Context, brokers []string, log *logrus.Logger) (sarama.ConsumerGroup, error) {
saramaConfig := sarama.NewConfig()
saramaConfig.Version = ProtocolVersion
// So we can know the partition and offset of messages.
saramaConfig.Producer.Return.Successes = true
saramaConfig.Consumer.Interceptors = []sarama.ConsumerInterceptor{NewOTelInterceptor(GroupID)}
consumerGroup, err := sarama.NewConsumerGroup(brokers, GroupID, saramaConfig)
if err != nil {
return nil, err
}
handler := groupHandler{
log: log,
}
err = consumerGroup.Consume(ctx, []string{Topic}, &handler)
if err != nil {
return nil, err
}
return consumerGroup, nil
}
type groupHandler struct {
log *logrus.Logger
}
func (g *groupHandler) Setup(_ sarama.ConsumerGroupSession) error {
return nil
}
func (g *groupHandler) Cleanup(_ sarama.ConsumerGroupSession) error {
return nil
}
func (g *groupHandler) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
for {
select {
case message := <-claim.Messages():
orderResult := pb.OrderResult{}
err := proto.Unmarshal(message.Value, &orderResult)
if err != nil {
return err
}
g.log.WithContext(session.Context()).WithFields(logrus.Fields{
"orderId": orderResult.OrderId,
"messageTimestamp": message.Timestamp,
"messageTopic": message.Topic,
}).Info("Message claimed")
session.MarkMessage(message, "")
case <-session.Context().Done():
return nil
}
}
}