2

task_controller.rb:

def create
  response.headers["Content-Type"] = "text/javascript"
  task = Task.create(:blahblah)

  if task
    data = { :type => 'task', :method => 'create', :object => task }
    $redis.publish('message.test', data.to_json)
    send_created(task)
  else
    send_error
  end
end

stream_controller.rb:

def index
  response.headers['Content-Type'] = 'text/event-stream'
  redis = Redis.new
  redis.psubscribe('message.*') do |on|
    on.pmessage do |channel, pattern, data|
      response.stream.write("data: #{data}\n\n")
    end
  end
end

After the second connection from the same host, application it going down, and not response to any request. Logs are clear, so I don't know how to fix this problem.

kuatro
  • 481
  • 1
  • 5
  • 17
  • I think the problem is in Redis-server, because if I restart Redis service, application is going up, and responds correctly. – kuatro Aug 21 '13 at 18:58
  • I am not a Rails expert, but it looks like control leaves `index` method, presumably invalidating `response` object, before Redis listener has a chance to write anything to it. So when the next event arrives, it tries to write to an invalid `response` and application misbehaves. You probably need an infinite loop inside `index`, exiting on timer or client connection reset. – rkhayrov Aug 22 '13 at 09:37
  • 1
    Unfortunately that's not quite the problem. The request in fact is already blocking on the `psubscribe` method. That's why you need a multithreaded server like Puma, Unicorn, etc. The problem you're seeing is because your server (I'm guessing you encountered this in development) is running out of threads to handle the incoming connections. Sadly, I too have encountered this problem and have documented it in [my question](http://stackoverflow.com/q/18970458/877472). If you ever find a solution, please let me know, and I'll do the same. – Paul Richter Oct 08 '13 at 19:27

0 Answers0