2021-12-02 03:29:52 +00:00
|
|
|
package natsio
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/nats-io/nats.go"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Publish ...
|
|
|
|
func (js JetStream) Publish(stream, subject string, payload []byte) error {
|
|
|
|
channel := combineStreamAndSubjectName(stream, subject)
|
|
|
|
|
|
|
|
_, err := js.instance.PublishAsync(channel, payload)
|
|
|
|
if err != nil {
|
2022-03-18 03:06:11 +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 ...
|
|
|
|
func (js JetStream) Subscribe(stream, subject string, cb nats.MsgHandler) (*nats.Subscription, error) {
|
|
|
|
channel := combineStreamAndSubjectName(stream, subject)
|
|
|
|
|
|
|
|
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 03:06:11 +00:00
|
|
|
|
|
|
|
// PullSubscribe ...
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
2022-03-18 03:27:40 +00:00
|
|
|
// js := natsio.GetJetStream()
|
|
|
|
//
|
|
|
|
// sub, err := js.PullSubscribe("A_SUBJECT", "A_DURABLE")
|
2022-03-18 03:06:11 +00:00
|
|
|
//
|
|
|
|
// for {
|
|
|
|
// messages, err := sub.Fetch(10)
|
|
|
|
// // process each messages
|
|
|
|
// }
|
|
|
|
//
|
2022-03-18 03:49:07 +00:00
|
|
|
func (js JetStream) PullSubscribe(stream, subject, durable, consumer string) (*nats.Subscription, error) {
|
|
|
|
// Check if consumer existed
|
|
|
|
con, err := js.instance.ConsumerInfo(stream, consumer)
|
|
|
|
fmt.Println("con", con)
|
|
|
|
fmt.Println("err", err)
|
2022-03-18 03:55:13 +00:00
|
|
|
if con == nil {
|
|
|
|
info, err := js.instance.AddConsumer(stream, &nats.ConsumerConfig{
|
2022-03-18 04:00:26 +00:00
|
|
|
Durable: durable,
|
|
|
|
AckPolicy: nats.AckExplicitPolicy,
|
2022-03-18 03:55:13 +00:00
|
|
|
})
|
2022-03-18 03:58:34 +00:00
|
|
|
if err == nil {
|
2022-03-18 03:55:13 +00:00
|
|
|
fmt.Println("CONSUMER INFO", info)
|
|
|
|
} else {
|
|
|
|
fmt.Println("ADD CONSUMER ERROR", err)
|
|
|
|
}
|
|
|
|
}
|
2022-03-18 03:49:07 +00:00
|
|
|
|
2022-03-18 03:27:40 +00:00
|
|
|
sub, err := js.instance.PullSubscribe(subject, durable)
|
2022-03-18 03:06:11 +00:00
|
|
|
if err != nil {
|
2022-03-18 03:27:40 +00:00
|
|
|
msg := fmt.Sprintf("[NATS JETSTREAM] - pull subscribe subject #%s - durable #%s error: %s", subject, durable, err.Error())
|
2022-03-18 03:06:11 +00:00
|
|
|
return nil, errors.New(msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
return sub, nil
|
|
|
|
}
|