package locator import ( "context" "fmt" "git.hlsq.asia/alex/service-common/db/redis" "git.hlsq.asia/alex/service-common/log" ) // 玩家定位器 const ( KeyGatewayInfo = "gateway:info:%v" HFieldInfoGatewaySID = "gateway_sid_%v" ) var ( scriptBindGatewaySha1 string scriptBindGateway = ` local gateway_key = KEYS[1] local field_key = ARGV[1] local new_sid = ARGV[2] local existing_sid = redis.call("HGET", gateway_key, field_key) if existing_sid then return 0 end redis.call("HSET", gateway_key, field_key, new_sid) return 1 ` ) func NewLocator(ctx context.Context, usn int64, platform int32) *Locator { return &Locator{ ctx: ctx, usn: usn, platform: platform, } } type Locator struct { ctx context.Context usn int64 platform int32 } // BindGateway 绑定网关 func (l *Locator) BindGateway(gatewaySID int64) bool { if scriptBindGatewaySha1 == "" { scriptBindGatewaySha1 = redis.GetClient().ScriptLoad(l.ctx, scriptBindGateway).Val() } result, err := redis.GetClient().EvalSha( l.ctx, scriptBindGatewaySha1, []string{fmt.Sprintf(KeyGatewayInfo, l.usn)}, fmt.Sprintf(HFieldInfoGatewaySID, l.platform), gatewaySID, ).Int64() if err != nil { return false } if result == 0 { return false } return true } // UnbindGateway 解绑网关 func (l *Locator) UnbindGateway() { err := redis.GetClient().HDel(l.ctx, fmt.Sprintf(KeyGatewayInfo, l.usn), fmt.Sprintf(HFieldInfoGatewaySID, l.platform)).Err() if err != nil { log.Errorf("UnbindGateway Failed %v-%v, err: %v", l.usn, l.platform, err) } } // LocateGateway 定位网关 func (l *Locator) LocateGateway() int64 { sid, _ := redis.GetClient().HGet(l.ctx, fmt.Sprintf(KeyGatewayInfo, l.usn), fmt.Sprintf(HFieldInfoGatewaySID, l.platform)).Int64() return sid }