init project

This commit is contained in:
admin committed 2025-12-05 17:23:29 +08:00
commit d63cc8d9f5
33 files changed
+1529

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
package jetstream
import (
"context"
"github.com/nats-io/nats.go"
)
func NewContext(msg *nats.Msg) context.Context {
ctx := context.Background()
ctx = context.WithValue(ctx, "req_id", msg.Header.Get("req_id"))
return ctx
}
func NewMsg(ctx context.Context, subject string, data []byte) *nats.Msg {
header := nats.Header{}
header.Set("req_id", getContextValue(ctx, "req_id"))
return &nats.Msg{
Subject: subject,
Data: data,
Header: header,
}
}
func getContextValue(ctx context.Context, keyword string) string {
if ctx.Value(keyword) != nil {
if v, ok := ctx.Value(keyword).(string); ok {
return v
}
}
return ""
}
+58
View File
@@ -0,0 +1,58 @@
package jetstream
import (
"fmt"
nats "github.com/nats-io/nats.go"
log "github.com/sirupsen/logrus"
)
type Config struct {
Addr string `json:"addr"`
Token string `json:"token"`
}
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.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, err
}
js, err := nc.JetStream()
if err != nil {
return nil, err
}
log.Infof("jetStream Addr: %s", conf.Addr)
return &JetStream{
nc: nc,
JetStreamContext: js,
}, nil
}
func (c *JetStream) Close() {
c.nc.Close()
}