2014-10-29 129 views

回答

3

您可以添加一個超時塊​​這樣的:

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 
2

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!" 

主要這裏的想法是有一些發佈消息,在一段單獨的通道一次。訂閱客戶端還訂閱該特定頻道並檢查當前時間以決定是否已超時。

1

現在,您可以一步到位subscribe with a timeout

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