开发者

How to handle ruby post requests asynchronously with eventmachine

In the course of 开发者_高级运维a request in a rails app, I would like to post data to another server and have the original request complete without having to wait for the external post to resolve. I have the following code that posts properly, but still waits for the post to finish before moving on. I have tried moving EventMachine.stop outside of callback, but that just ends everything by calling errback. What do I do?

EventMachine.run {
    http = EventMachine::HttpRequest.new(url).post :body => {body}
    http.errback { p 'Uh oh'; EM.stop }
    http.callback {
      p http.response
      EventMachine.stop
    }
  }

EDIT: I'm not married to eventmachine for this. If there is a better solution I'm all ears.


There is a simple solution which is to just create a new thread and let do the job, one library which may (or not) help you doing this properly is https://github.com/tra/spawn . I never used it myself but I think it may be a good fit for your need.

I love Eventmachine and use it on most of my projects (work or personnal) but it requires more work to make it works with rails and you still need to be really careful about what libraries you are using and how to not block the reactor.

Note that you also need to be careful with treads if doing anything blocking but most libraries today are built to not block the interpreter (in 1.9 at least)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜