wait for NATS

This commit is contained in:
mr 2025-06-24 08:49:53 +02:00
parent e84d262f38
commit 2c8dcbe93d
2 changed files with 38 additions and 29 deletions

View File

@ -110,7 +110,7 @@ func (a *API) SubscribeRouter(infos []*beego.ControllerInfo) {
}
}
}
nats.SetNATSPub("api", DISCOVERY, discovery)
go nats.SetNATSPub("api", DISCOVERY, discovery)
}
// CheckRemotePeer checks the state of a remote peer

View File

@ -3,6 +3,7 @@ package tools
import (
"encoding/json"
"strings"
"time"
"cloud.o-forge.io/core/oc-lib/config"
"cloud.o-forge.io/core/oc-lib/logs"
@ -53,10 +54,11 @@ func (s *natsCaller) ListenNats(chanName string, exec func(msg map[string]interf
log.Error().Msg(" -> NATS_SERVER is not set")
return
}
for {
nc, err := nats.Connect(config.GetConfig().NATSUrl)
if err != nil {
log.Error().Msg(" -> Could not reach NATS server : " + err.Error())
return
time.Sleep(1 * time.Minute)
continue
}
ch := make(chan *nats.Msg, 64)
subs, err := nc.ChanSubscribe(chanName, ch)
@ -70,6 +72,8 @@ func (s *natsCaller) ListenNats(chanName string, exec func(msg map[string]interf
json.Unmarshal(msg.Data, &map_mess)
exec(map_mess)
}
break
}
}
// SetNATSPub sets a message to the NATS server
@ -77,9 +81,11 @@ func (o *natsCaller) SetNATSPub(dataName string, method NATSMethod, data interfa
if config.GetConfig().NATSUrl == "" {
return " -> NATS_SERVER is not set"
}
for {
nc, err := nats.Connect(config.GetConfig().NATSUrl)
if err != nil {
return " -> Could not reach NATS server : " + err.Error()
time.Sleep(1 * time.Minute)
continue
}
defer nc.Close()
js, err := json.Marshal(data)
@ -88,7 +94,10 @@ func (o *natsCaller) SetNATSPub(dataName string, method NATSMethod, data interfa
}
err = nc.Publish(method.GenerateKey(dataName), js) // Publish the message on the NATS server with a channel name based on the data name (or whatever start) and the method
if err != nil {
return " -> " + err.Error() // Return an error if the message could not be published
time.Sleep(1 * time.Minute)
continue
}
break
}
return ""
}