em-synchrony.rb 使用 Fibers 实现了此功能,但我会选择 1.8 MRI 的非 Fibre 版本。
EM.run do
http = EM::Protocols::HttpClient2.connect("www.google.com", 80)
request = http.get("/")
request.callback do
puts request.status
EM.stop
end
end
em-synchrony.rb 使用 Fibers 实现了此功能,但我会选择 1.8 MRI 的非 Fibre 版本。
EM.run do
http = EM::Protocols::HttpClient2.connect("www.google.com", 80)
request = http.get("/")
request.callback do
puts request.status
EM.stop
end
end
EM.run do
http1 = EventMachine::HttpRequest.new('http://example.com/1').get
http1.callback do
p http1.response
end
http2 = EventMachine::HttpRequest.new('http://example.com/2').get
http2.callback do
p http2.response
end
end
如果您可以在 EventMachine 之外查看,Typhoeus是一个易于使用的 HTTP 客户端,它附带 Hydra,它提供了并行处理多个请求的能力。
我用它做了几件事,而且很容易设置。这是我前几天写的一些未经测试的代码:
require 'typhoeus'
hydra = Typhoeus::Hydra.new(:max_concurrency => 10)
urls.each do |url|
request = Typhoeus::Request.new(url)
request.on_complete do |resp|
filename = resp.request.url.split('/').last
puts "writing #{filename}"
File.open(filename, 'w') do |fo|
fo.write resp.body
end
end
puts "queuing #{ url }"
hydra.queue(request)
end
hydra.run