我正在执行大量 HTTP 请求,并选择 HTTP::Async 来完成这项工作。我要发出超过 1000 个请求,如果我只是执行以下操作(请参阅下面的代码),许多请求在处理时就会超时,因为处理到达它们之前可能需要数十分钟:
for my $url (@urls) {
$async->add(HTTP::Request->new(GET => $url));
}
while (my $resp = $async->wait_for_next_response) {
# use $resp
}
所以我决定每次做25个请求,但是我想不出用代码来表达的方法。
我尝试了以下方法:
while (1) {
L25:
for (1..25) {
my $url = shift @urls;
if (!defined($url)) {
last L25;
}
$async->add(HTTP::Request->new(GET => $url));
}
while (my $resp = $async->wait_for_next_response) {
# use $resp
}
}
然而,这并不能很好地工作,因为它现在太慢了。现在,它会等待,直到所有 25 个请求都已处理完毕,然后再添加另外 25 个请求。因此,如果还剩下 2 个请求,则它不会执行任何操作。我必须等待所有请求都处理完毕才能添加下一批 25 个请求。
我怎样才能改进这个逻辑$async
在处理记录时做一些事情,但也要确保它们不会超时。
你已经很接近了,你只需要结合这两种方法就可以了! :-)
未经测试,因此将其视为伪代码。特别是我不确定是否total_count
是正确的使用方法,文档没有说。你也可以有一个$active_requests
反驳你++
添加请求时并且--
当你得到回应时。
while (1) {
# if there aren't already 25 requests "active", then add more
while (@urls and $async->total_count < 25) {
my $url = shift @urls;
$async->add( ... );
}
# deal with any finished requests right away, we wait for a
# second just so we don't spin in the main loop too fast.
while (my $response = $async->wait_for_next_response(1)) {
# use $response
}
# finish the main loop when there's no more work
last unless ($async->total_count or @urls);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)