-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
92 lines (77 loc) · 1.59 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"fmt"
"time"
"github.com/confluentinc/confluent-kafka-go/kafka"
)
type Producer struct {
p *kafka.Producer
closeChan chan struct{}
}
func NewProducer() *Producer {
p, err := kafka.NewProducer(
&kafka.ConfigMap{
"bootstrap.servers": "localhost:9092",
},
)
if err != nil {
panic(err)
}
closeChan := make(chan struct{}, 1)
go func() {
defer close(closeChan)
for {
select {
case msg := <-p.Events():
switch ev := msg.(type) {
case *kafka.Message:
m := ev
if m.TopicPartition.Error != nil {
fmt.Printf("Delivery failed: %v\n", m.TopicPartition.Error)
} else {
fmt.Printf(
"Delivered message to topic %s [%d] at offset %v\n",
*m.TopicPartition.Topic, m.TopicPartition.Partition, m.TopicPartition.Offset,
)
}
default:
// fmt.Printf("Ignored event: %s\n", ev)
}
case <-closeChan:
fmt.Println("closing ...")
break
}
}
}()
return &Producer{
p: p,
closeChan: closeChan,
}
}
func (p *Producer) Send(data []byte) error {
fmt.Println("sending message ", string(data))
topic := "test"
p.p.ProduceChannel() <- &kafka.Message{
TopicPartition: kafka.TopicPartition{
Topic: &topic,
Partition: kafka.PartitionAny,
},
Value: data,
}
fmt.Println("sended ", string(data))
return nil
}
func (p *Producer) Close() {
p.p.Close()
p.closeChan <- struct{}{}
}
func main() {
p := NewProducer()
p.Send([]byte("1"))
p.Send([]byte("2"))
p.Send([]byte("3"))
p.Send([]byte("4"))
time.Sleep(time.Second * 10)
p.Close()
time.Sleep(time.Second * 2)
}