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 {
|
|
|
|
channel := combineStreamAndSubjectName(js.streamName, subject)
|
2021-12-02 03:29:52 +00:00
|
|
|
|
|
|
|
_, err := js.instance.PublishAsync(channel, payload)
|
|
|
|
if err != nil {
|
2022-03-18 04:28:49 +00:00
|
|
|
msg := fmt.Sprintf("[NATS JETSTREAM] - publish message to subject #%s error: %s", channel, err.Error())
|
2021-12-02 03:29:52 +00:00
|
|
|
return errors.New(msg)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Subscribe ...
|
2022-12-04 15:10:05 +00:00
|
|
|
func (js JetStream) Subscribe(subject string, cb nats.MsgHandler) (*nats.Subscription, error) {
|
|
|
|
channel := combineStreamAndSubjectName(js.streamName, subject)
|
2021-12-02 03:29:52 +00:00
|
|
|
|
|
|
|
sub, err := js.instance.Subscribe(channel, cb)
|
|
|
|
if err != nil {
|
|
|
|
msg := fmt.Sprintf("[NATS JETSTREAM] - subscribe subject %s error: %s", channel, err.Error())
|
|
|
|
return nil, errors.New(msg)
|
|
|
|
}
|
|
|
|
return sub, nil
|
|
|
|
}
|
2022-03-18 04:28:49 +00:00
|
|
|
|
|
|
|
// PullSubscribe ...
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
|
|
|
// js := natsio.GetJetStream()
|
|
|
|
//
|
|
|
|
// sub, err := js.PullSubscribe("A_SUBJECT", "A_SUBJECT", "A_CONSUMER")
|
|
|
|
//
|
2022-12-04 15:10:05 +00:00
|
|
|
// for {
|
|
|
|
// messages, err := sub.Fetch(10)
|
|
|
|
// // process each messages
|
|
|
|
// }
|
|
|
|
func (js JetStream) PullSubscribe(subject, consumer string) (*nats.Subscription, error) {
|
|
|
|
channel := combineStreamAndSubjectName(js.streamName, subject)
|
2022-03-18 04:28:49 +00:00
|
|
|
|
|
|
|
// Check if consumer existed
|
2022-12-04 15:10:05 +00:00
|
|
|
con, err := js.GetConsumerInfo(consumer)
|
2022-03-18 04:28:49 +00:00
|
|
|
if con == nil || err != nil {
|
2022-12-04 15:10:05 +00:00
|
|
|
msg := fmt.Sprintf("[NATS JETSTREAM] - pull subscribe consumer %s not existed in stream %s", consumer, js.streamName)
|
2022-03-18 04:28:49 +00:00
|
|
|
return nil, errors.New(msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Pull
|
|
|
|
sub, err := js.instance.PullSubscribe(channel, consumer)
|
|
|
|
if err != nil {
|
|
|
|
msg := fmt.Sprintf("[NATS JETSTREAM] - pull subscribe subject #%s - consumer #%s error: %s", channel, consumer, err.Error())
|
|
|
|
return nil, errors.New(msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
return sub, nil
|
|
|
|
}
|