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
|
|
|
|
2022-12-15 11:04:03 +00:00
|
|
|
if js.cfg.Debug {
|
2022-12-15 10:34:47 +00:00
|
|
|
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
|
|
|
|
2022-12-15 11:04:03 +00:00
|
|
|
if js.cfg.Debug {
|
2022-12-15 10:34:47 +00:00
|
|
|
fmt.Printf("[natsio.JetStream] subscribe new message from subject #%s \n", subject)
|
|
|
|
}
|
|
|
|
|
2021-12-02 03:29:52 +00:00
|
|
|
return sub, nil
|
|
|
|
}
|
2022-03-18 04:28:49 +00:00
|
|
|
|
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)
|
2022-03-18 04:28:49 +00:00
|
|
|
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)
|
2022-03-18 04:28:49 +00:00
|
|
|
return nil, errors.New(msg)
|
|
|
|
}
|
|
|
|
|
2022-12-15 10:34:47 +00:00
|
|
|
// pull
|
|
|
|
sub, err := js.instance.PullSubscribe(subject, consumer)
|
2022-03-18 04:28:49 +00:00
|
|
|
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())
|
2022-03-18 04:28:49 +00:00
|
|
|
return nil, errors.New(msg)
|
|
|
|
}
|
|
|
|
|
2022-12-15 11:04:03 +00:00
|
|
|
if js.cfg.Debug {
|
2022-12-15 10:34:47 +00:00
|
|
|
fmt.Printf("[natsio.JetStream] pull subscribe new message from subject #%s \n", subject)
|
|
|
|
}
|
|
|
|
|
2022-03-18 04:28:49 +00:00
|
|
|
return sub, nil
|
|
|
|
}
|