This repository has been archived by the owner on Jul 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pulsar.go
86 lines (73 loc) · 2.53 KB
/
pulsar.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
package messaging
import (
"context"
"github.com/apache/pulsar-client-go/pulsar"
"github.com/pkg/errors"
)
// PulsarClient : A client for creating Pulsar producers and consumers
type PulsarClient struct {
internalClient pulsar.Client
}
// NewPulsarClient : Create a new Pulsar client
func NewPulsarClient(pulsarURL string) (Client, error) {
client, err := pulsar.NewClient(pulsar.ClientOptions{URL: pulsarURL})
if err != nil {
return nil, errors.Wrap(err, "failed to create pulsar client")
}
return &PulsarClient{internalClient: client}, nil
}
// CreateProducer : Create a new Pulsar producer
func (client *PulsarClient) CreateProducer(topic string) (Producer, error) {
producer, err := client.internalClient.CreateProducer(pulsar.ProducerOptions{Topic: topic})
if err != nil {
return nil, errors.Wrap(err, "failed to create pulsar producer")
}
return &PulsarProducer{internalProducer: producer}, nil
}
// CreateConsumer : Create a new Pulsar consumer
func (client *PulsarClient) CreateConsumer(topic string, subscriptionName string) (Consumer, error) {
consumer, err := client.internalClient.Subscribe(pulsar.ConsumerOptions{
Topic: topic,
SubscriptionName: subscriptionName,
Type: pulsar.Shared,
})
if err != nil {
return nil, errors.Wrap(err, "failed to create pulsar consumer")
}
return &PulsarConsumer{internalConsumer: consumer}, nil
}
// Close : Close the Pulsar client
func (client *PulsarClient) Close() {
client.internalClient.Close()
}
// PulsarProducer : A producer for sending messages to an Apache Pulsar topic
type PulsarProducer struct {
internalProducer pulsar.Producer
}
// Send : Send a message payload through the Pulsar producer
func (producer *PulsarProducer) Send(payload []byte) error {
_, err := producer.internalProducer.Send(context.Background(), &pulsar.ProducerMessage{
Payload: payload,
})
return err
}
// Close : Close the Pulsar producer
func (producer *PulsarProducer) Close() {
producer.internalProducer.Close()
}
// PulsarConsumer : A consumer for receiving messages from an Apache Pulsar topic
type PulsarConsumer struct {
internalConsumer pulsar.Consumer
}
// Receive : Receive a message through the Pulsar consumer
func (consumer *PulsarConsumer) Receive() ([]byte, error) {
message, err := consumer.internalConsumer.Receive(context.Background())
if err != nil {
return nil, errors.Wrap(err, "failed to receive message")
}
return message.Payload(), nil
}
// Close : Close the Pulsar consumer
func (consumer *PulsarConsumer) Close() {
consumer.internalConsumer.Close()
}