2014-10-29 3 views
0

Redis 채널에서 최대 2 초 동안 메시지를 기다리고 싶습니다. 구독을 만료 시키거나 시간 제한을 설정하고 코드 차단을 중단하고 싶습니다.Ruby 및 Redis : 구독 제한 시간 설정

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을 사용하고 있습니다. 소스를 검색했지만 구독에 시간 초과 옵션이 없습니다.

답변

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