Use map to improve message delivery time

This commit is contained in:
LittleSheep 2024-05-07 20:45:02 +08:00
parent 7c5c9d03d1
commit 32be79557a
2 changed files with 16 additions and 9 deletions

View File

@ -5,14 +5,13 @@ import (
"git.solsynth.dev/hydrogen/messaging/pkg/services" "git.solsynth.dev/hydrogen/messaging/pkg/services"
"github.com/gofiber/contrib/websocket" "github.com/gofiber/contrib/websocket"
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"
"github.com/samber/lo"
) )
func messageGateway(c *websocket.Conn) { func messageGateway(c *websocket.Conn) {
user := c.Locals("principal").(models.Account) user := c.Locals("principal").(models.Account)
// Push connection // Push connection
services.WsConn[user.ID] = append(services.WsConn[user.ID], c) services.ClientRegister(user, c)
// Event loop // Event loop
var task models.UnifiedCommand var task models.UnifiedCommand
@ -42,7 +41,5 @@ func messageGateway(c *websocket.Conn) {
} }
// Pop connection // Pop connection
services.WsConn[user.ID] = lo.Filter(services.WsConn[user.ID], func(item *websocket.Conn, idx int) bool { services.ClientUnregister(user, c)
return item != c
})
} }

View File

@ -5,14 +5,24 @@ import (
"github.com/gofiber/contrib/websocket" "github.com/gofiber/contrib/websocket"
) )
var WsConn = make(map[uint][]*websocket.Conn) var wsConn = make(map[uint]map[*websocket.Conn]bool)
func CheckOnline(user models.Account) bool { func ClientRegister(user models.Account, conn *websocket.Conn) {
return len(WsConn[user.ID]) > 0 if wsConn[user.ID] == nil {
wsConn[user.ID] = make(map[*websocket.Conn]bool)
}
wsConn[user.ID][conn] = true
}
func ClientUnregister(user models.Account, conn *websocket.Conn) {
if wsConn[user.ID] == nil {
wsConn[user.ID] = make(map[*websocket.Conn]bool)
}
delete(wsConn[user.ID], conn)
} }
func PushCommand(userId uint, task models.UnifiedCommand) { func PushCommand(userId uint, task models.UnifiedCommand) {
for _, conn := range WsConn[userId] { for conn := range wsConn[userId] {
_ = conn.WriteMessage(1, task.Marshal()) _ = conn.WriteMessage(1, task.Marshal())
} }
} }