简体   繁体   中英

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM