2011-11-06 50 views

回答

3

爲什麼你需要一個網絡圖書館處理的並行?這正是線程的目的。

require "open-uri" 

fetcher = lambda do |uri| 
    puts "Started fetching #{uri}" 
    puts open(uri).read 
    puts "Stopped fetching #{uri}" 
end 

thread1 = Thread.new("http://localhost:9292", &fetcher) 
thread2 = Thread.new("http://localhost:9293", &fetcher) 

thread1.join 
thread2.join 

此外,我不明白「執行更好」是什麼意思。核心庫通常足以勝任核心工作。你對Net :: HTTP有任何問題嗎?

+2

百頭巨怪存在,飛馳處理這個問題,我看不出有任何理由,你會在這裏重新發明輪子。 – coreyward

1

您可以使用Parallel gem,它應該可以在任何Ruby HTTP庫中使用。

0

不知道它是否表現更好Typhoeus,但你可以使用Eventmacheine + em-http-request。有一個發送多個請求的例子。

require 'eventmachine' 
require 'em-http' 

EventMachine.run { 
    multi = EventMachine::MultiRequest.new 

    reqs = [ 
    'http://google.com/', 
    'http://google.ca:81/' 
    ] 

    reqs.each_with_index do |url, idx| 
    http = EventMachine::HttpRequest.new(url, :connect_timeout => 1) 
    req = http.get 
    multi.add idx, req 
    end 

    multi.callback do 
    p multi.responses[:callback].size 
    p multi.responses[:errback].size 
    EventMachine.stop 
    end 
} 

https://github.com/igrigorik/em-http-request