-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
76 lines (62 loc) · 2.05 KB
/
main.go
File metadata and controls
76 lines (62 loc) · 2.05 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
67
68
69
70
71
72
73
74
75
76
package main
import (
"context"
"fmt"
"log"
"sync"
"github.com/segmentio/kafka-go"
)
// consumeMessages sets up a Kafka consumer to process messages concurrently.
// It improves throughput for high-volume systems by leveraging goroutines.
func consumeMessages(brokerAddress, topic, groupID string, maxConcurrency int) error {
// Initialize a new Kafka reader (consumer) with the given configuration
reader := kafka.NewReader(kafka.ReaderConfig{
Brokers: []string{brokerAddress},
Topic: topic,
GroupID: groupID,
})
defer reader.Close()
var wg sync.WaitGroup
sem := make(chan struct{}, maxConcurrency) // Semaphore to limit concurrency
for {
// Read messages from Kafka
m, err := reader.ReadMessage(context.Background())
if err != nil {
return fmt.Errorf("error while reading message: %v", err)
}
// Acquire a semaphore
sem <- struct{}{}
// Increment wait group counter
wg.Add(1)
// Process the message in a new goroutine
go func(msg kafka.Message) {
defer wg.Done() // Decrement wait group counter when done
defer func() { <-sem }() // Release the semaphore
// Simulate message processing
log.Printf("Processing message: topic=%s partition=%d offset=%d key=%s value=%s",
msg.Topic, msg.Partition, msg.Offset, string(msg.Key), string(msg.Value))
// You can add your message processing logic here
}(m)
}
// Wait for all goroutines to complete
wg.Wait()
return nil
}
// main is the entry point of the program.
// It demonstrates consuming messages concurrently from a Kafka topic.
func main() {
// Kafka broker address
brokerAddress := "localhost:9092"
// Kafka topic to consume messages from
topic := "example-topic"
// Consumer group ID
groupID := "example-group"
// Maximum number of concurrent message processors
maxConcurrency := 5
// Start consuming messages concurrently
if err := consumeMessages(brokerAddress, topic, groupID, maxConcurrency); err != nil {
log.Fatalf("Failed to consume messages: %v", err)
}
// Optional: Log completion
fmt.Println("Concurrent message processing complete. Exiting.")
}