natsio/jetstream_pubsub.go

60 lines
1.6 KiB
Go

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