可选项
This commit is contained in:
parent
2fd042eb47
commit
1c3b27e900
|
|
@ -10,11 +10,10 @@ import (
|
|||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func NewNats(url string, options ...nats.Option) *Nats {
|
||||
return &Nats{
|
||||
func NewNats(url string, options ...NatsOption) *Nats {
|
||||
n := &Nats{
|
||||
url: url,
|
||||
subject: "MINOTAUR_CROSS",
|
||||
options: options,
|
||||
messagePool: synchronization.NewPool[*Message](1024*100, func() *Message {
|
||||
return new(Message)
|
||||
}, func(data *Message) {
|
||||
|
|
@ -22,11 +21,9 @@ func NewNats(url string, options ...nats.Option) *Nats {
|
|||
data.Packet = nil
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func NewNatsWithSubject(url, subject string, options ...nats.Option) *Nats {
|
||||
n := NewNats(url, options...)
|
||||
n.subject = subject
|
||||
for _, option := range options {
|
||||
option(n)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
|
|
@ -39,9 +36,11 @@ type Nats struct {
|
|||
}
|
||||
|
||||
func (slf *Nats) Init(server *server.Server, packetHandle func(serverId int64, packet []byte)) (err error) {
|
||||
slf.conn, err = nats.Connect(slf.url, slf.options...)
|
||||
if err != nil {
|
||||
return err
|
||||
if slf.conn == nil {
|
||||
slf.conn, err = nats.Connect(slf.url, slf.options...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = slf.conn.Subscribe(fmt.Sprintf("%s_%d", slf.subject, server.GetID()), func(msg *nats.Msg) {
|
||||
message := slf.messagePool.Get()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,28 @@
|
|||
package corss
|
||||
|
||||
import "github.com/nats-io/nats.go"
|
||||
|
||||
type NatsOption func(n *Nats)
|
||||
|
||||
// WithNatsSubject 通过对应的主题名称创建
|
||||
// - 默认为:MINOTAUR_CROSS
|
||||
func WithNatsSubject(subject string) NatsOption {
|
||||
return func(n *Nats) {
|
||||
n.subject = subject
|
||||
}
|
||||
}
|
||||
|
||||
// WithNatsOptions 通过nats自带的可选项创建连接
|
||||
func WithNatsOptions(options ...nats.Option) NatsOption {
|
||||
return func(n *Nats) {
|
||||
n.options = options
|
||||
}
|
||||
}
|
||||
|
||||
// WithNatsConn 指定通过特定的连接创建
|
||||
// - 这将导致 WithNatsOptions 失效
|
||||
func WithNatsConn(conn *nats.Conn) NatsOption {
|
||||
return func(n *Nats) {
|
||||
n.conn = conn
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue