-
Notifications
You must be signed in to change notification settings - Fork 179
/
kafka.go
49 lines (42 loc) · 934 Bytes
/
kafka.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
package pendingtx
import (
"context"
"encoding/json"
rpctypes "github.com/okex/exchain/app/rpc/types"
"github.com/segmentio/kafka-go"
)
type KafkaClient struct {
Topic string
*kafka.Writer
}
func NewKafkaClient(addrs []string, topic string) *KafkaClient {
return &KafkaClient{
Topic: topic,
Writer: kafka.NewWriter(kafka.WriterConfig{
Brokers: addrs,
Topic: topic,
Balancer: &kafka.LeastBytes{},
}),
}
}
type KafkaMsg struct {
Topic string `json:"topic"`
Source interface{} `json:"source"`
Data *rpctypes.Transaction `json:"data"`
}
func (kc *KafkaClient) Send(hash []byte, tx *rpctypes.Transaction) error {
msg, err := json.Marshal(KafkaMsg{
Topic: kc.Topic,
Data: tx,
})
if err != nil {
return err
}
// Automatic retries and reconnections on errors.
return kc.WriteMessages(context.Background(),
kafka.Message{
Key: hash,
Value: msg,
},
)
}