-
Notifications
You must be signed in to change notification settings - Fork 0
/
producer.go
73 lines (59 loc) · 1.32 KB
/
producer.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
package runtime
import (
"fmt"
"context"
"github.com/apache/pulsar-client-go/pulsar"
)
type Producer interface {
Send(payload []byte) error
SendStruct(msg *Message) error
GetConnectionInfo() string
Close()
}
type PulsarProducer struct {
client pulsar.Client
producer pulsar.Producer
url string
topic string
}
func (p *PulsarProducer) GetConnectionInfo() string {
return fmt.Sprintf("url: %s, topic: %s", p.url, p.topic)
}
func (p *PulsarProducer) Send(payload []byte) error {
_, err := p.producer.Send(context.Background(), &pulsar.ProducerMessage{
Payload: payload,
})
return err
}
func (p *PulsarProducer) SendStruct(msg *Message) error {
_, err := p.producer.Send(context.Background(), &pulsar.ProducerMessage{
Value: msg,
})
return err
}
func (p *PulsarProducer) Close() {
p.producer.Close()
p.client.Close()
}
func NewPulsarProducer(URL string, topic string, schema *string) (*PulsarProducer, error) {
client, err := pulsar.NewClient(pulsar.ClientOptions{
URL: URL,
})
if err != nil {
return nil, err
}
option := pulsar.ProducerOptions{
Topic: topic,
}
if schema != nil {
option.Schema = pulsar.NewJSONSchema(*schema, nil)
}
producer, err := client.CreateProducer(option)
if err != nil {
return nil, err
}
return &PulsarProducer{
client: client,
producer: producer,
}, nil
}