2
我想了解如何使用异步sinatra和EventMachine的组合使用偶数web服务器。与Sinatra和EventMachine相同的长时间运行操作的多个http请求
在下面的代码中,每个'/'上的请求都会生成一个新的异步http请求给谷歌。是否有一个优雅的解决方案来检测请求是否正在执行并等待执行?
如果我在'/'上有100个并发请求,则会向Google后端生成100个请求。有一种方法来检测已经存在的后端请求并等待其执行会更好。
感谢您的回答。
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 [email protected] || @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
这给每秒的请求数量非常高。凉!
彪马和独角兽并不是服务器。 – 2013-09-16 15:08:31
@JakeHoffner固定 – 2013-09-17 08:35:05