liuhaijun e94826ce29 add server
Change-Id: I0760f17f6a01c0121b59fcbfafc666032dbc30af
2024-09-19 09:44:15 +00:00

44 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package data
import (
c "git.inspur.com/sbg-jszt/cfn/cfn-schedule/config"
"git.inspur.com/sbg-jszt/cfn/cfn-schedule/pkg/log"
"github.com/nats-io/nats.go"
"time"
)
var Nc *nats.Conn
func initNats() {
var err error
// 此种链接方式在Ubuntu桌面版上报错dial tcp: missing address
//url := fmt.Sprintf("nats://%s:%s@%s", c.Config.Nats.User, c.Config.Nats.Password, c.Config.Nats.Url)
//Nc, err = nats.Connect(url)
opts := []nats.Option{nats.Name("NATS Sample Publisher")}
opts = append(opts, nats.UserInfo(c.Config.Nats.User, c.Config.Nats.Password))
log.Infof("Nats connect url: %s", "nats://"+c.Config.Nats.Url)
log.Infof("Nats connect options: %v", opts)
Nc, err = nats.Connect("nats://"+c.Config.Nats.Url, opts...)
if err != nil {
log.Errorf("连接nats失败%s, %s, %s", c.Config.Nats.Url, c.Config.Nats.User, c.Config.Nats.Password)
panic("Nats connection failed" + err.Error())
}
go func() {
defer func() {
if r := recover(); r != nil {
log.Errorf("recover check nats connection: %v", r)
}
}()
const interval = time.Minute * 2
ticker := time.NewTicker(interval)
for _ = range ticker.C {
if !Nc.IsConnected() {
Nc, _ = nats.Connect("nats://"+c.Config.Nats.Url, opts...)
}
}
}()
}