natsio/server_reqres.go

72 lines
1.8 KiB
Go
Raw Normal View History

2021-12-02 03:29:52 +00:00
package natsio
import (
"errors"
"fmt"
"time"
"github.com/nats-io/nats.go"
)
// Default timeout 10s
const requestTimeout = 10 * time.Second
// Request ...
2022-12-15 10:34:47 +00:00
func (s Server) Request(subject string, payload []byte) (*nats.Msg, error) {
timeout := requestTimeout
2022-12-15 11:04:03 +00:00
if s.cfg.RequestTimeout > 0 {
timeout = s.cfg.RequestTimeout
}
2022-12-15 10:34:47 +00:00
msg, err := s.instance.Request(subject, payload, timeout)
2022-08-30 08:55:20 +00:00
if errors.Is(err, nats.ErrNoResponders) {
2022-12-15 10:34:47 +00:00
fmt.Printf("[natsio.Server] no responders for subject: %s \n", subject)
2022-12-15 11:04:03 +00:00
} else if s.cfg.Debug {
2022-12-15 10:34:47 +00:00
fmt.Printf("[natsio.Server] send request to subject #%s successfully \n", subject)
2022-08-30 08:55:20 +00:00
}
2022-12-15 10:34:47 +00:00
2022-08-30 08:55:20 +00:00
return msg, err
2021-12-02 03:29:52 +00:00
}
// RequestWithBindData ...
2022-12-15 10:34:47 +00:00
func (s Server) RequestWithBindData(subject string, payload []byte, result interface{}) error {
msg, err := s.Request(subject, payload)
2022-12-21 02:56:36 +00:00
fmt.Println("data", msg.Data)
fmt.Println("err", err.Error())
if msg == nil || err != nil {
2022-12-21 02:56:36 +00:00
fmt.Println("1")
return err
}
2022-12-21 02:56:36 +00:00
fmt.Println("2")
// map
2022-12-21 02:56:36 +00:00
return BytesToInterface(msg.Data, result)
}
2021-12-02 03:29:52 +00:00
// Reply ...
2022-12-15 10:34:47 +00:00
func (s Server) Reply(msg *nats.Msg, payload []byte) error {
return s.instance.Publish(msg.Reply, payload)
2021-12-02 03:29:52 +00:00
}
// Subscribe ...
2022-12-15 10:34:47 +00:00
func (s Server) Subscribe(subject string, cb nats.MsgHandler) (*nats.Subscription, error) {
sub, err := s.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.Server] 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
2021-12-02 03:29:52 +00:00
return sub, nil
}
2022-08-10 10:52:00 +00:00
2022-10-18 04:46:04 +00:00
// QueueSubscribe ...
2022-12-15 10:34:47 +00:00
func (s Server) QueueSubscribe(subject, queue string, cb nats.MsgHandler) (*nats.Subscription, error) {
sub, err := s.instance.QueueSubscribe(subject, queue, cb)
2022-10-18 04:46:04 +00:00
if err != nil {
2022-12-15 10:34:47 +00:00
msg := fmt.Sprintf("[natsio.Server] queue subscribe subject %s, queue %s error: %s", subject, queue, err.Error())
2022-10-18 04:46:04 +00:00
return nil, errors.New(msg)
}
2022-12-15 10:34:47 +00:00
2022-10-18 04:46:04 +00:00
return sub, nil
}