0

I'm making a simple game engine, which implements room manipulation.

I was thinking a lot and still have doubts that I'm making rooms not in the valid way.

Here's the scenario.

1) There's one static room, where users are able to 'register'. 2) after certain number of users are registered, it should create dynamic room and put these certain number of users in that room and make them quit the static room.

So, if we run this in multiple instances and let's say we're waiting for 2 users.

2 users join the static room -> create new room (in redis) -> enter these two players in that room (subscribe) -> make those players to leave static room (queue-like system).

Now what I think is a problem.

2 users join the static room -> before creating new room, one other player joins static room (different node instance) -> create new room -> move two players there -> other instance still thinks there's enough users to create new room -> something weird happens.

Is this correct? How should I implement the queue style room?

4

2 回答 2

1

您需要原子操作:将所有这 4 个步骤放入事务中。使用 Redis,您可以使用TransactionLua Scripting来实现它。

使用 lua 脚本,您可以拥有这样的脚本:

-- add new user to static room
redis.call('lpush', 'static_room', ARGV[1])

-- if the number of static room reaches the limit
local num = redis.call('llen', 'static_room')
if num == 2  then
    -- get the room number for a new dynamic room
    local new_dynamic_room_num = redis.call('incr', 'dynamic_room');
    local dynamic_room = 'dynamic_room' .. new_dynamic_room_num

    -- move all users from static room to dynamic room
    while true do
        local num = redis.call('llen', 'static_room')

        if num == 0 then break end

        redis.call('rpoplpush', 'static_room', dynamic_room)
    end
end

由于 lua 脚本是原子执行的,在我们完成将所有用户从静态房间移动到动态房间之前,没有其他用户可以加入静态房间。

于 2016-10-16T08:39:43.770 回答
0

一种解决方案可能是让所有未连接的玩家进入一个唯一的节点实例,该实例负责创建房间并将玩家分配到这些房间。然后,一旦将它们分配到给定的房间,它会将它们重定向到负责该房间的节点实例。

于 2016-10-16T06:13:43.857 回答