-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
68 lines (57 loc) · 1.38 KB
/
main.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
package main
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/confluentinc/confluent-kafka-go/v2/kafka"
)
func main() {
serv := getHost()
c, err := kafka.NewConsumer(&kafka.ConfigMap{
"bootstrap.servers": serv,
"group.id": "foo",
"auto.offset.reset": "earliest"})
if err != nil {
fmt.Printf("Failed to create consumer: %s", err)
os.Exit(1)
}
topic := "demo"
err = c.SubscribeTopics([]string{topic}, nil)
if err != nil {
fmt.Printf("Failed to subscribe to topics: %s", err)
os.Exit(1)
}
// Set up a channel for handling Ctrl-C, etc
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)
// Process messages
run := true
for run {
select {
case sig := <-sigchan:
fmt.Printf("Caught signal %v: terminating\n", sig)
run = false
default:
ev, err := c.ReadMessage(100 * time.Millisecond)
if err != nil {
// Errors are informational and automatically handled by the consumer
continue
}
fmt.Printf("Consumed event from topic %s: key = %-10s value = %s\n",
*ev.TopicPartition.Topic, string(ev.Key), string(ev.Value))
}
}
c.Close()
}
func getHost() string {
const KAFKA_BROKER_SERV = "KAFKA_BROKER_SERV"
host := os.Getenv(KAFKA_BROKER_SERV)
if len(host) == 0 {
host = "localhost:9092"
}
log.Printf("Consumer connecting to Kafka broker at [%v]", host)
return host
}