如何在非机架中使用带有红宝石事件机的光纤?

时间:2014-01-13 08:19:01

标签: ruby httprequest nonblocking eventmachine fibers

所以基本上我的目标是获得某种轻量级的ruby守护进程(或者sidekiq / resque worker),它可以处理作业并通过http通知其他应用程序。应用程序本身不需要接收http请求,因此没有机架可以保持尽可能轻量级。我可以在 loop {}

中运行相当多的ruby代码

因此,尝试不使用EventMachine'反应器模式并使用光纤方法。我在哪里将EM.run或EM.stop放在这个上下文中 Thread.new {EM.run} 似乎不是光纤感知的,所以添加它没有给出回调?是否有em-synchrony替代方案?

#slow=true injects a sleep 3, so page 2 callback should output faster
require 'em-http-request'
require 'fiber'
def http_get(url)
  f = Fiber.current
  http = EventMachine::HttpRequest.new(url).get

  # resume fiber once http call is done
  http.callback { f.resume(http) }
  http.errback  { f.resume(http) }

  return Fiber.yield
end

puts "fetching some data from database for request params"
EventMachine.run do
  Fiber.new{
    page = http_get('http://localhost:3000/status?slow=true')
    puts "notified external page it responded with: #{page.response_header.status}"
  }.resume
  Fiber.new{
    page = http_get('http://localhost:4000/status')
    puts "notified external page 2 it responded with: #{page.response_header.status}"
  }.resume
  puts "Finishised notification task"
end
puts "Moving on to next task as fast as possible"

1 个答案:

答案 0 :(得分:-3)

避免重新发明轮子,使用EM::Synchrony或甚至更好地切换到celluloidcelluloid-io,因为EM似乎已经不再需要维护