-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathexample_consumer_group_test.go
72 lines (54 loc) · 1.74 KB
/
example_consumer_group_test.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
// (c) Copyright IBM Corp. 2023
//go:build go1.17
// +build go1.17
package instasarama_test
import (
"context"
"github.com/IBM/sarama"
instana "github.com/instana/go-sensor"
"github.com/instana/go-sensor/instrumentation/instasarama"
"github.com/opentracing/opentracing-go"
)
// This example demonstrates how to instrument a Kafka consumer group using instasarama
// and extract the trace context to ensure continuation. Error handling is omitted for brevity.
func Example_consumerGroup() {
sensor := instana.NewSensor("my-service")
brokers := []string{"localhost:9092"}
topics := []string{"records", "more-records"}
conf := sarama.NewConfig()
conf.Version = sarama.V0_11_0_0
client, _ := sarama.NewConsumerGroup(brokers, "my-service-consumers", conf)
defer client.Close()
ctx := context.Background()
consumer := instasarama.WrapConsumerGroupHandler(&Consumer{sensor: sensor}, sensor)
// start consuming
for {
_ = client.Consume(ctx, topics, consumer)
// ...
}
}
type Consumer struct {
sensor instana.TracerLogger
}
func (*Consumer) Setup(sarama.ConsumerGroupSession) error {
// setup consumer
return nil
}
func (*Consumer) Cleanup(sarama.ConsumerGroupSession) error {
// cleanup consumer
return nil
}
func (c *Consumer) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
for msg := range claim.Messages() {
c.processMessage(msg)
session.MarkMessage(msg, "")
}
return nil
}
func (c *Consumer) processMessage(msg *sarama.ConsumerMessage) {
// extract trace context and start a new span
parentCtx, _ := instasarama.SpanContextFromConsumerMessage(msg, c.sensor)
sp := c.sensor.Tracer().StartSpan("process-message", opentracing.ChildOf(parentCtx))
defer sp.Finish()
// process message
}