timetable-mgr/messaging/client.go

53 lines
1.3 KiB
Go
Raw Normal View History

2023-07-18 00:25:13 +01:00
package messaging
2023-07-18 14:09:28 +01:00
import (
"git.fjla.uk/owlboard/timetable-mgr/helpers"
"git.fjla.uk/owlboard/timetable-mgr/log"
2023-07-18 14:09:28 +01:00
"github.com/go-stomp/stomp/v3"
)
var Client *stomp.Conn
2023-07-18 14:09:28 +01:00
// Initialises the connection to the STOMP server
func StompInit(cfg *helpers.Configuration) {
Client = dial(cfg.NrodUser, cfg.NrodPass)
2023-07-18 14:09:28 +01:00
}
2023-07-19 13:22:55 +01:00
// Connects the STOMP file to the Network Rail MQ Server
func dial(user, pass string) *stomp.Conn {
2023-07-18 14:09:28 +01:00
conn, err := stomp.Dial("tcp", "publicdatafeeds.networkrail.co.uk:61618",
stomp.ConnOpt.Login(user, pass),
2023-07-18 14:09:28 +01:00
stomp.ConnOpt.HeartBeat(15000, 15000),
stomp.ConnOpt.Header("client-id", user+"-mq-client"),
2023-07-18 14:09:28 +01:00
)
if err != nil {
2024-04-14 19:03:13 +01:00
log.Fatal("Unable to connect to STOMP Client: " + err.Error())
2024-04-15 20:36:33 +01:00
conn.Disconnect()
2023-07-18 14:09:28 +01:00
}
2023-07-19 13:22:55 +01:00
2024-04-14 19:03:13 +01:00
log.Info("Initialised STOMP Client")
2023-07-18 14:09:28 +01:00
return conn
}
2023-07-19 13:22:55 +01:00
// Handles graceful disconnection of the STOMP client, falls back to
// a force disconnect if this fails.
func Disconnect(conn *stomp.Conn) {
2023-07-18 14:09:28 +01:00
if conn != nil {
err := conn.Disconnect()
2024-04-14 19:03:13 +01:00
log.Warn("Disconnected STOMP Client")
2023-07-18 14:09:28 +01:00
if err != nil {
conn.MustDisconnect()
2024-04-14 19:03:13 +01:00
log.Error("STOMP Disconnection failed, forced disconnect")
2023-07-18 14:09:28 +01:00
}
2023-07-19 13:22:55 +01:00
return
2023-07-18 14:09:28 +01:00
}
2024-04-14 19:03:13 +01:00
log.Error("STOMP Disconnect failed, next connection attempt may fail")
2024-04-15 20:36:33 +01:00
err := Client.Disconnect()
if err != nil {
Client.MustDisconnect()
log.Warn("STOMP Disconnect failed, forced disconnection")
}
log.Info("STOMP Client disconnected")
2023-07-18 14:09:28 +01:00
2024-04-15 20:36:33 +01:00
}