我正在构建一个分布式网络爬虫,并试图最大限度地利用每台机器的资源。我通过 Iterator 在 EventMachine 中运行解析函数,并使用 em-http-request 发出异步 HTTP 请求。目前我有 100 次同时运行的迭代,似乎我无法通过这个级别。如果我增加迭代次数,它不会影响爬行速度。但是,我只有 10-15% 的 cpu 负载和 20-30% 的网络负载,因此还有足够的空间可以更快地爬行。
我正在使用 Ruby 1.9.2。有没有办法改进代码以有效地使用资源,或者我什至做错了?
def start_job_crawl
@redis.lpop @queue do |link|
if link.nil?
EventMachine::add_timer( 1 ){ start_job_crawl() }
else
#parsing link, using asynchronous http request,
#doing something with the content
parse(link)
end
end
end
#main reactor loop
EM.run {
EM.kqueue
@redis = EM::Protocols::Redis.connect(:host => "127.0.0.1")
@redis.errback do |code|
puts "Redis error: #{code}"
end
#100 parallel 'threads'. Want to increase this
EM::Iterator.new(0..99, 100).each do |num, iter|
start_job_crawl()
end
}