redis跨服分布式全局锁
📅 2026/8/4 7:42:47
👁️ 阅读次数
📝 编程学习
问题描述,在玩家切换场景之前,我存了一个坐标。在玩家再次切换场景的时候,我取出上次存的坐标,居然不是我存的坐标 然后看log save_last_scene 10007500009521 101 43 57 ------remsg--------- { ["scene_id"] = 101, ["pos"] = { ["x"] = 37, ["y"] = 66, }, ["reconnect"] = false, } last_x 和 last_y不是保存的值 看起来是redis保存失败了? 进程 logic function Oper.User.SetGameInfo(userid, game_info) if(not game_info)then return end -- 更新redis local user_cache = redis_wraper.wrap_table('user_info_cache','userid') local userinfo = user_cache:select(userid) userinfo.game_info = game_info userinfo.room_id = game_info.room_id user_cache:save(userid, userinfo) player_mgr.set(userid, "game_info",game_info) end 进程 scene function CMD.save_last_scene(userid, scene_id, x, y) local t = redis_wraper.wrap_table("user_info_cache","userid") local userinfo = t:select(userid) userinfo.last_scene_id = scene_id userinfo.last_x = x userinfo.last_y = y t:save(userid, userinfo) print("save_last_scene",userid,scene_id,x,y) end local function build_enter_scene_remsg(mbr) local userid = mbr.userid local user_info_cache = proxy.call_game(nil, nil, 'get_user_info_cache', userid) or {} if user_info_cache.last_scene_id and user_info_cache.last_scene_id == g_data.scene_id then mbr.cur_pos.x = user_info_cache.last_x mbr.cur_pos.y = user_info_cache.last_y end local remsg = { scene_id = g_data.scene_id, pos = mbr.cur_pos, reconnect = mbr.reconnect, state = g_data.state } mbr.reconnect = nil --重连标记是一次性的,用完清空 -- 战斗ID相关逻辑 if mbr.battleId then local battleRecord = Handler.Battle.GetBattle(mbr.battleId) if battleRecord then for _, battleUserId in pairs(battleRecord.userList or {}) do if battleUserId == userid then remsg.battleId = mbr.battleId break end end end end print("------remsg---------",tostring(remsg)) return remsg end 玩家切换场景回先通知 logic 调用函数 SetGameInfo 然后通知 scene调用 save_last_scene。 理论上如果是一个地方存就没问题,但是我们先不讨论设计的问题,先讨论保存2次出现bug. 其实就是要加锁,redis一样存在不同进程同时操作同一个数据的问题,修改会失败。 下面是修改后的 function Oper.User.SetGameInfo(userid, game_info) if(not game_info)then return end -- 更新redis(整条读写包进跨服全局锁,和 save_last_scene 串行化,避免互相覆盖 last_x/last_y) local lock_ok = redis_wraper.redis_global_lock(userid, function() local user_cache = redis_wraper.wrap_table('user_info_cache','userid') local userinfo = user_cache:select(userid) logger.fmt.info("[set_game_info_lock] GOT_LOCK userid:%s read_last_x:%s read_last_y:%s -> set game_info.scene_id:%s", tostring(userid), tostring(userinfo and userinfo.last_x), tostring(userinfo and userinfo.last_y), tostring(game_info and game_info.scene_id)) userinfo.game_info = game_info userinfo.room_id = game_info.room_id user_cache:save(userid, userinfo) logger.fmt.info("[set_game_info_lock] SAVED userid:%s keep_last_x:%s keep_last_y:%s", tostring(userid), tostring(userinfo.last_x), tostring(userinfo.last_y)) end) logger.fmt.info("[set_game_info_lock] DONE userid:%s lock_ok:%s", tostring(userid), tostring(lock_ok)) player_mgr.set(userid, "game_info",game_info) end function CMD.save_last_scene(userid, scene_id, x, y) logger.fmt.info("[save_last_scene_lock] REQ userid:%s scene_id:%s x:%s y:%s", tostring(userid), tostring(scene_id), tostring(x), tostring(y)) local lock_ok = redis_wraper.redis_global_lock(userid, function() local t = redis_wraper.wrap_table("user_info_cache","userid") local userinfo = t:select(userid) logger.fmt.info("[save_last_scene_lock] GOT_LOCK userid:%s read_last_x:%s read_last_y:%s -> write x:%s y:%s", tostring(userid), tostring(userinfo and userinfo.last_x), tostring(userinfo and userinfo.last_y), tostring(x), tostring(y)) userinfo.last_scene_id = scene_id userinfo.last_x = x userinfo.last_y = y t:save(userid, userinfo) end) logger.fmt.info("[save_last_scene_lock] DONE userid:%s lock_ok:%s", tostring(userid), tostring(lock_ok)) print("save_last_scene",userid,scene_id,x,y) end 加锁函数 -- ====================== 【跨服分布式全局锁】逻辑服/游戏服共用,防止并发脏写 user_info_cache ====================== -- 作用:以 userid 为维度,跨服/多机 原子串行化 Redis 整条 read-modify-write -- 用法:redis_wraper.redis_global_lock(userid, function() ... end) local REDIS_LOCK_PREFIX = "redis:global:lock:" local LOCK_EXPIRE = 300 -- 0.3秒自动释放:临界区是 Redis 整条读写(亚毫秒),0.3s足够;缩短崩溃恢复窗口 local LOCK_RETRY = 5 -- 瞬时竞态下(另一服正持有)最多重试次数,避免输家直接跳过写入 local LOCK_RETRY_TICK = 1 -- 每次重试间隔(skynet tick, 1 tick≈10ms),5次≈50ms 远小于 300ms TTL function redis_wraper.redis_global_lock(userid, func) local key = REDIS_LOCK_PREFIX .. tostring(userid) local uuid = skynet.self() .. ":" .. skynet.now() local conn = redis_wraper.get_raw_conn(userid) -- 原子加锁 (SET key value NX PX 毫秒),失败时短暂退避重试 local acquired = false for _ = 1, LOCK_RETRY do local ok = conn:set(key, uuid, "NX", "PX", LOCK_EXPIRE) if ok then acquired = true break end skynet.sleep(LOCK_RETRY_TICK) end if not acquired then logger.error("[RedisLock] 获取Redis全局锁失败 userid=" .. tostring(userid)) return nil end -- 执行业务逻辑(整条读改写都在临界区内) local suc, err = pcall(func) if not suc then logger.error("[RedisLock] Redis操作失败 userid=" .. tostring(userid), err) end -- 原子解锁 (Lua脚本,只有持有者能释放,防误删) local script = [[ if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) end return 0 ]] conn:eval(script, 1, key, uuid) return true end -- ====================== 【跨服锁结束】======================
编程学习
技术分享
实战经验