【问题标题】:Ruby and Redis: set a timeout for subscribtionsRuby 和 Redis:为订阅设置超时
【发布时间】:2014-10-29 06:56:04
【问题描述】:

我想在 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 :(

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

【问题讨论】:

    标签: ruby-on-rails ruby redis publish-subscribe


    【解决方案1】:

    您现在可以一键subscribe with a timeout

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

    【讨论】:

      【解决方案2】:

      你可以像这样添加一个超时块​​:

      require 'timeout'
      
      begin
        Timeout.timeout(2) do      
          redis.subscribe(channel) do |on|
            on.message do |channel, message|
              # ...
            end
          end
        end
      rescue Timeout::Error
        # handle error: show user a message?
      end
      

      【讨论】:

      【解决方案3】:

      redis-rb pubsub 实现中没有超时选项。然而,它可以很容易地用你已经拥有的工具来构建:

      require 'redis'
      
      channel = 'test'
      timeout_channel = 'test_timeout'
      
      timeout = 3
      
      redis = Redis.new
      
      redis.subscribe(channel, time_channel) do |on|
        timeout_at = Time.now + timeout
      
        on.message do |channel, message|
          redis.unsubscribe if channel == timeout_channel && Time.now >= timeout_at
        end
      
        # not the best way to do it, but we need something publishing to timeout_channel
        Thread.new {
          sleep timeout
          Redis.new.publish timeout_channel, 'ping'
        }
      end
      
      #This line is never reached if no message is sent to channel :(
      puts "here we are!"
      

      这里的主要想法是让某些东西偶尔将消息发布到单独的频道。订阅客户端还订阅该特殊频道并检查当前时间以确定它是否已经超时。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-10
        • 1970-01-01
        • 2016-12-20
        • 1970-01-01
        相关资源
        最近更新 更多