WebSocketServer/modules/redis/redis.go

64 lines
1.3 KiB
Go

package redis
import (
"context"
gocnjhelper "git.clickandjoin.umbach.dev/ClickandJoin/go-cnj-helper"
"github.com/redis/go-redis/v9"
)
var ctx = context.Background()
var rdb *redis.Client
func Init() {
rdb = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
err := rdb.Ping(ctx).Err()
if err != nil {
gocnjhelper.LogFatal("Redis ping failed")
}
}
func AddUserWebSocketSessionId(userId string, wsSessionId string) {
cmd := rdb.LPush(ctx, userId, wsSessionId)
gocnjhelper.LogDebugf("b %s", cmd)
}
func RemoveUserWebSocketSessionId(userId string, wsSessionId string) {
cmd := rdb.LRem(ctx, userId, -1, wsSessionId)
gocnjhelper.LogDebugf("rem %s", cmd)
}
func IsUserConnectedToAnyWebSocketServer(userId string) bool {
cmd := rdb.Exists(ctx, userId)
gocnjhelper.LogDebugf("exists b %s", cmd)
return cmd.Val() == 1
}
func ExistsUserWebSocketSessionId(userId string, wsSessionId string) bool {
wsSessions := rdb.LRange(ctx, userId, 0, -1)
gocnjhelper.LogDebugf("found ws %s", wsSessions.Val())
return isWsSessionIdInList(wsSessions.Val(), wsSessionId)
}
func isWsSessionIdInList(wsSessions []string, wsSessionId string) bool {
for _, item := range wsSessions {
if item == wsSessionId {
return true
}
}
return false
}