natsio/jetstream_pubsub.go

60 lines
1.6 KiB
Go
Raw Normal View History

2021-12-02 03:29:52 +00:00
package natsio
import (
"errors"
"fmt"
"github.com/nats-io/nats.go"
)
// Publish ...
2022-12-04 15:10:05 +00:00
func (js JetStream) Publish(subject string, payload []byte) error {
2022-12-15 10:34:47 +00:00
_, err := js.instance.PublishAsync(subject, payload)
2021-12-02 03:29:52 +00:00
if err != nil {
2022-12-15 10:34:47 +00:00
msg := fmt.Sprintf("[natsio.JetStream] publish message to subject #%s error: %s", subject, err.Error())
2021-12-02 03:29:52 +00:00
return errors.New(msg)
}
2022-12-15 10:34:47 +00:00
if js.debug {
fmt.Printf("[natsio.JetStream] published a message to subject #%s \n", subject)
}
2021-12-02 03:29:52 +00:00
return nil
}
// Subscribe ...
2022-12-04 15:10:05 +00:00
func (js JetStream) Subscribe(subject string, cb nats.MsgHandler) (*nats.Subscription, error) {
2022-12-15 10:34:47 +00:00
sub, err := js.instance.Subscribe(subject, cb)
2021-12-02 03:29:52 +00:00
if err != nil {
2022-12-15 10:34:47 +00:00
msg := fmt.Sprintf("[natsio.JetStream] subscribe subject %s error: %s", subject, err.Error())
2021-12-02 03:29:52 +00:00
return nil, errors.New(msg)
}
2022-12-15 10:34:47 +00:00
if js.debug {
fmt.Printf("[natsio.JetStream] subscribe new message from subject #%s \n", subject)
}
2021-12-02 03:29:52 +00:00
return sub, nil
}
2022-12-04 15:10:05 +00:00
func (js JetStream) PullSubscribe(subject, consumer string) (*nats.Subscription, error) {
2022-12-15 10:34:47 +00:00
// check if consumer existed
2022-12-04 15:10:05 +00:00
con, err := js.GetConsumerInfo(consumer)
if con == nil || err != nil {
2022-12-15 10:34:47 +00:00
msg := fmt.Sprintf("[natsio.JetStream] pull subscribe consumer %s not existed in stream %s", consumer, js.streamName)
return nil, errors.New(msg)
}
2022-12-15 10:34:47 +00:00
// pull
sub, err := js.instance.PullSubscribe(subject, consumer)
if err != nil {
2022-12-15 10:34:47 +00:00
msg := fmt.Sprintf("[natsio.JetStream] pull subscribe subject #%s - consumer #%s error: %s", subject, consumer, err.Error())
return nil, errors.New(msg)
}
2022-12-15 10:34:47 +00:00
if js.debug {
fmt.Printf("[natsio.JetStream] pull subscribe new message from subject #%s \n", subject)
}
return sub, nil
}