2012-07-30 80 views
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 

这给每秒的请求数量非常高。凉!

回答

1

您不必一定要使用sinatra/async来使其变为平坦,只需使用一个服务器(Thin,Rainbows!,Goliath)运行即可。

看看em-synchrony制作多个并行的请求,而不引入意大利面条回调代码的例子:

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 

是的,您可以在西纳特拉行动中运行这些。

另请参阅Faraday,特别是EM适配器。

+1

彪马和独角兽并不是服务器。 – 2013-09-16 15:08:31

+0

@JakeHoffner固定 – 2013-09-17 08:35:05