Ruby和Redis:为订阅设置超时

sin*_*ina 3 ruby ruby-on-rails publish-subscribe redis

我想在Redis通道中等待消息最多2秒钟,然后我希望订阅过期/超时并停止阻止我的代码。

redis = Redis.new

redis.subscribe(channel) do |on|
  on.message do |channel, message|
    # ...
  end
end

# This line is never reached if no message is sent to channel :(
Run Code Online (Sandbox Code Playgroud)

我正在使用https://github.com/redis/redis-rb。我在源中进行了搜索,但没有找到订阅的超时选项。

Sun*_*nny 6

现在您可以一步一步订阅超时

redis.subscribe_with_timeout(5, channel) do |on|
  on.message do |channel, message|
    # ...
  end
end
Run Code Online (Sandbox Code Playgroud)