-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
66 lines (52 loc) · 1.88 KB
/
main.go
File metadata and controls
66 lines (52 loc) · 1.88 KB
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
package main
import (
"context"
"log"
"time"
"github.com/segmentio/kafka-go"
)
// main is the entry point for the Kafka lag monitoring program.
// It demonstrates setting up a Kafka consumer, tracking and logging message lag in Kafka topics.
func main() {
brokerAddress := "localhost:9092"
topic := "example-topic"
partition := 0
// Create a new Kafka reader (consumer) with specified broker and topic settings.
reader := kafka.NewReader(kafka.ReaderConfig{
Brokers: []string{brokerAddress},
Topic: topic,
Partition: partition,
})
defer reader.Close()
log.Println("Starting Kafka consumer to monitor message lag...")
// Start a loop to continuously read messages
for {
// Set a context with timeout to prevent blocking indefinitely
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Fetch the next message, if available
msg, err := reader.ReadMessage(ctx)
if err != nil {
log.Printf("Error reading message: %v", err)
continue
}
// Compute the lag based on the difference between message and current time
lag := time.Since(msg.Time)
// Log the message details and computed lag for monitoring purposes
log.Printf("Received message: %s | Lag: %v ", string(msg.Value), lag)
// Handle business logic with the message here (e.g., processing)
handleMessage(msg)
}
}
// handleMessage processes the message received from Kafka
// This is a placeholder for where business logic would be implemented to handle and process messages.
func handleMessage(m kafka.Message) {
// Example processing step
log.Printf("Processing message: %s", string(m.Value))
// Simulate processing time
time.Sleep(1 * time.Second)
}
// To run the program, ensure Kafka is running locally
// and the specified topic (`example-topic`) exists.
// You can produce messages to test lag monitoring
// with a Kafka producer tool or another program.