使用 ruby 进行异步 HTTP 请求
我有一个充满请求的rabbitmq队列,我想以HTTP GET方式异步发送请求,而不需要等待每个请求响应。现在我很困惑,线程还是 EM 哪个更好用?我目前使用它的方式类似于以下内容,但很高兴知道这里是否有更好的实现和更好的性能,因为它是程序的一个非常关键的部分:
AMQP.start(:host => "localhost") do |connection|
queue = MQ.queue("some_queue")
queue.subscribe do |body|
EventMachine::HttpRequest.new('http://localhost:9292/faye').post :body => {:message => body.to_json }
end
end
通过上面的代码,是系统将等待每个请求完成后再开始下一个请求?如果这里有任何提示,我将非常感激
I have a rabbitmq queue full of requests and I want to send the requests as an HTTP GET asynchronously, without the need to wait for each request response. now I'm confused of what is better to use, threads or just EM ? The way i'm using it at the moment is something like the following , but it would be great to know if there is any better implementation with better performance here since it is a very crucial part of the program :
AMQP.start(:host => "localhost") do |connection|
queue = MQ.queue("some_queue")
queue.subscribe do |body|
EventMachine::HttpRequest.new('http://localhost:9292/faye').post :body => {:message => body.to_json }
end
end
With the code above, is the system will wait for each request to finish before starting the next one ? and if there any tips here I would highly appreciate it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
HTTP 是同步的,因此您必须等待回复。如果你想模拟一个异步环境,你可以有一个线程池,并将每个请求传递给一个等待回复的线程,然后返回池中直到下一个请求。您可以向线程发送一个回调函数以在回复完成时使用,或者您可以立即返回一个未来的回复对象,这允许您推迟等待回复,直到您真正需要回复数据。
另一种方法是拥有一个进程池,每个进程都在处理请求、等待回复等。
在这两种情况下,您都必须有一个足够大的池,否则您仍然会等待一些进程。时间。
HTTP is synchronous so you have to wait for the replies. If you want to simulate an async environment that you could have a thread pool and pass each request to a thread which will wait for the reply, then go back in the pool until the next request. You would either send the thread a callback function to use when the reply is finished or you would immediately return a future reply object, which allows you to put off waiting for the reply until you actually need the reply data.
The other way is to have a pool of processes each one of which is processing a request, waiting for the reply, etc.
In both cases, you have to have a pool that is big enough or else you will still end up waiting some of the time.