我想在Redis通道中等待最多2秒的消息,然後我希望訂閱到期/超時並停止阻止我的代碼。我正在使用https://github.com/redis/redis-rb。我在源文件中搜索,但發現訂閱沒有超時選項。Ruby和Redis:爲訂閱設置超時
0
A
回答
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
相關問題
- 1. 如何將超時設置爲Google Pubsub發佈者和訂閱者?
- 2. Nats.io隊列訂閱行爲超時
- 3. 如何設置redis連接超時?
- 4. 訂閱模式Redis與Python
- 5. 設置訂閱對象
- 6. 設置條紋訂閱續訂付款
- 7. 使用Mysql設置連接超時Ruby
- 8. Azure Redis超時
- 9. 如何設置redis-cli命令的超時時間?
- 10. AngularJS:爲$ evalAsync設置超時
- 11. Redis發佈/訂閱數據持久性
- 12. 無法訂閱Redis的通道Laravel 5.2
- 13. Redis - 最大訂閱數/連接數?
- 14. 消息持久 - Redis的發佈/訂閱
- 15. Redis和Faye中的分級發佈/訂閱和推送通知
- 16. 如何爲SQL Server設置Ruby ODBC驅動程序的超時?
- 17. 設置超時設置的套接字有時會在閱讀時失速
- 18. 超時設置
- 19. 設置超時?
- 20. 強制Redis超時
- 21. 在MySQL中設置訂閱日期
- 22. 設置月度訂閱的模式
- 23. redis:設置redis的密碼
- 24. 只有在Redis中存在密鑰時才訂閱頻道
- 25. 爲NetworkObject.MapNetworkDrive設置超時時間
- 26. 訂閱和取消訂閱活動
- 27. Redis發佈和訂閱不支持動態密鑰
- 28. 如何使用yii2和redis進行訂閱?
- 29. 爲BLE掃描連續訂閱和取消訂閱Observable
- 30. Rx處置訂閱