是否可以在Rails中创建一个订阅Redis消息通道的线程?

时间:2015-03-21 07:24:49

标签: ruby-on-rails multithreading unicorn

我正在尝试在Rails中创建一个线程来订阅Redis的消息通道。有没有办法做到这一点?我正在使用独角兽。

我试图在unicorn配置中这样做:

after_fork do |server, worker|

  Thread.new do
    begin
      $redis.subscribe(:one, :two) do |on|
        on.subscribe do |channel, subscriptions|
          puts "Subscribed to ##{channel} (#{subscriptions} subscriptions)"
        end
        on.message do |channel, message|
          puts "##{channel}: #{message}"
          $redis.unsubscribe if message == "exit"
        end
        on.unsubscribe do |channel, subscriptions|
          puts "Unsubscribed from ##{channel} (#{subscriptions} subscriptions)"
        end
      end
    rescue Redis::BaseConnectionError => error
      puts "#{error}, retrying in 1s"
      sleep 1
      retry
    end
  end
end

但它会使unicorn服务器无法处理任何Web请求。我想如果我使用不同的线程来订阅Redis,它就不会阻止主线程;我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:0)

这里的问题是红宝石中的GIL;并且Redis ruby​​的客户端库正在使用一个循环来进行订阅命令。