-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
67 lines (57 loc) · 1.3 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
package main
import (
"github.com/Shopify/sarama"
"fmt"
"os"
"os/signal"
"strings"
"log"
)
type Message struct {
key string
value string
offset int64
partition int32
topic string
}
func (m *Message) String() string {
return fmt.Sprintf("topic:[%s] parition:[%d] offset:[%d] key:[%s] value:%s", m.topic, m.partition, m.offset, m.key, m.value)
}
func main() {
if len(os.Args) < 2 {
fmt.Println(os.Args[0], "<broker1;broker2;...> <topic>")
os.Exit(0)
}
brokers := os.Args[1]
topic := os.Args[2]
consumer, err := sarama.NewConsumer(strings.Split(brokers, ";"), nil)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
partitions, err := consumer.Partitions(topic)
log.Println("partitions:", partitions)
if err != nil {
fmt.Println(err)
os.Exit(2)
}
for _, partition := range partitions {
pcon, err := consumer.ConsumePartition(topic, partition, sarama.OffsetNewest)
if err != nil {
fmt.Println(err)
os.Exit(3)
}
go func() {
mc := pcon.Messages()
for {
msg := <-mc
m := Message{key:string(msg.Key), value:string(msg.Value), topic:msg.Topic, partition:msg.Partition, offset:msg.Offset}
fmt.Println(m.String())
}
}()
}
killChan := make(chan os.Signal)
signal.Notify(killChan, os.Kill, os.Interrupt)
kill := <-killChan
fmt.Println(kill)
}