package jetstream import ( "errors" "fmt" "strings" "time" nats "github.com/nats-io/nats.go" log "github.com/sirupsen/logrus" ) type Config struct { Enabled bool `mapstructure:"enabled"` Addr string `mapstructure:"addr"` Token string `mapstructure:"token"` ConnectTimeout time.Duration `mapstructure:"connect_timeout"` } func (cfg Config) Validate() error { if cfg.Enabled && (strings.TrimSpace(cfg.Addr) == "" || cfg.ConnectTimeout <= 0) { return errors.New("enabled jetstream requires addr and positive connect_timeout") } return nil } type JetStream struct { nats.JetStreamContext nc *nats.Conn } func NewJetStreamBroker(conf Config) (*JetStream, error) { nc, err := nats.Connect(conf.Addr, nats.Token(conf.Token), nats.Timeout(conf.ConnectTimeout), nats.DisconnectErrHandler(func(conn *nats.Conn, err error) { log.Errorf("jetStream disconnect: %v", err) }), nats.ReconnectHandler(func(conn *nats.Conn) { log.Infof("jetStream reconnect") }), nats.ClosedHandler(func(conn *nats.Conn) { log.Infof("jetStream closed") }), nats.DiscoveredServersHandler(func(conn *nats.Conn) { log.Infof("jetStream discovered") }), nats.ErrorHandler(func(conn *nats.Conn, subscription *nats.Subscription, e error) { subDesc := "" if subscription != nil { subDesc = fmt.Sprintf(" subject:%s queue:%s", subscription.Subject, subscription.Queue) } log.Errorf("jetStream%s err:%v", subDesc, e) }), ) if err != nil { return nil, errors.New("connect nats failed") } js, err := nc.JetStream() if err != nil { nc.Close() return nil, errors.New("initialize jetstream failed") } log.Info("jetstream connected") return &JetStream{ nc: nc, JetStreamContext: js, }, nil } func (c *JetStream) Close() { c.nc.Close() }