我正在尝试理解如何使用异步sinatra和EventMachine相结合的偶发web服务器。
在下面的代码中,“/”上的每个请求都会向google生成一个新的异步http请求。是否有一个优雅的解决方案来检测请求已经在进行并等待其执行?
如果我在'/‘上有100个并发请求,这将生成100个对google后端的请求。最好有一种方法来检测已经存在的后端请求并等待其执行。
谢谢你的回答。
require 'sinatra'
require 'json'
require 'eventmachine'
require 'em-http-request'
require 'sinatra/async'
Sinatra.register Sinatra::Async
def get_data
puts "Start request"
http = EventMachine::HttpRequest.new("http://www.google.com").get
http.callback {
puts "Request completed"
yield http.response
}
end
aget '/' do
get_data {|data| body data}
end更新
实际上,我发现您可以向同一个http请求添加几个回调。因此,很容易实现:
class Request
def get_data
if !@http || @http.response_header.status != 0
#puts "Creating new request"
@http = EventMachine::HttpRequest.new("http://www.bbc.com").get
end
#puts "Adding callback"
@http.callback do
#puts "Request completed"
yield @http.response
end
end
end
$req = Request.new
aget '/' do
$req.get_data {|data| body data}
end这提供了非常多的请求每秒。凉爽的!
发布于 2012-08-12 01:51:10
您根本不需要使用sinatra/异步来使其平滑,只需使用一个偶发服务器(Thin,Rainbows!,Goliath)即可运行它。
看看同步性的一个例子,它可以在不引入意大利回调代码的情况下发出多个并行请求:
require "em-synchrony"
require "em-synchrony/em-http"
EventMachine.synchrony do
multi = EventMachine::Synchrony::Multi.new
multi.add :a, EventMachine::HttpRequest.new("http://www.postrank.com").aget
multi.add :b, EventMachine::HttpRequest.new("http://www.postrank.com").apost
res = multi.perform
p "Look ma, no callbacks, and parallel HTTP requests!"
p res
EventMachine.stop
end是的,你可以在你的辛纳特拉行动中运行这个。
还可以看看法拉第,特别是EM适配器。
https://stackoverflow.com/questions/11725105
复制相似问题