gpt4 book ai didi

http - 赛璐珞和高性能 HTTP 请求

转载 作者:可可西里 更新时间:2023-11-01 16:44:21 24 4
gpt4 key购买 nike

我尝试将现有的爬虫从 EventMachine 切换到 Celluloid。为了接触 Celluloid,我在通过 Nginx 提供服务的 linux 机器上生成了一堆静态文件,每个文件 150 kB。

底部的代码应该可以正常工作,但是代码有一个我不明白的问题:代码应该生成最多 50 个线程,因为线程池大小为 50,但它生成了 180 个线程。如果我将池大小增加到 100,则会生成 330 个线程。那里出了什么问题?

此代码的简单复制和粘贴应该适用于每个框,因此欢迎任何提示:)

#!/usr/bin/env jruby

require 'celluloid'
require 'open-uri'

URLS = *(1..1000)

@@requests = 0
@@responses = 0
@@total_size = 0

class Crawler
include Celluloid

def fetch(id)
uri = URI("http://data.asconix.com/#{id}")
puts "Request ##{@@requests += 1} -> #{uri}"
begin
req = open(uri).read
rescue Exception => e
puts e
end
end
end

URLS.each_slice(50).map do |idset|
pool = Crawler.pool(size: 50)
crawlers = idset.to_a.map do |id|
begin
pool.future(:fetch, id)
rescue Celluloid::DeadActorError, Celluloid::MailboxError
end
end
crawlers.compact.each do |resp|
$stdout.print "Response ##{@@responses += 1} -> "
if resp.value.size == 150000
$stdout.print "OK\n"
@@total_size += resp.value.size
else
$stdout.print "ERROR\n"
end
end
pool.terminate
puts "Actors left: #{Celluloid::Actor.all.to_set.length} -- Alive: #{Celluloid::Actor.all.to_set.select(&:alive?).length}"
end

$stdout.print "Requests total: #{@@requests}\n"
$stdout.print "Responses total: #{@@responses}\n"
$stdout.print "Size total: #{@@total_size} bytes\n"

顺便说一句,当我在 each_slice 循环之外定义池时,也会出现同样的问题:

....
@pool = Crawler.pool(size: 50)

URLS.each_slice(50).map do |idset|
crawlers = idset.to_a.map do |id|
begin
@pool.future(:fetch, id)
rescue Celluloid::DeadActorError, Celluloid::MailboxError
end
end
crawlers.compact.each do |resp|
$stdout.print "Response ##{@@responses += 1} -> "
if resp.value.size == 150000
$stdout.print "OK\n"
@@total_size += resp.value.size
else
$stdout.print "ERROR\n"
end
end
puts "Actors left: #{Celluloid::Actor.all.to_set.length} -- Alive: #{Celluloid::Actor.all.to_set.select(&:alive?).length}"
end

最佳答案

你用的是什么 ruby ? jRubyRubinius 等等?那些版本是什么?

我问的原因是,每个 ruby 的线程处理方式不同。您似乎在描述的是为主管和任务添加的线程。查看您发帖的日期,纤程很可能实际上正在成为 native 线程,这可能会让它看起来像是在使用 jRuby。此外,使用 Futures 经常会调用内部线程池,这与您的池无关。

由于这些原因以及您可以寻找的其他类似原因,这就是为什么您的线程数高于池要求的原因。虽然这有点旧,所以也许您可以跟进您是否仍然有这个问题,并发布输出。

关于http - 赛璐珞和高性能 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12343659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com