本文介绍了如何在 Perl 中发出并行 HTTP 请求,并按顺序接收它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Perl,我正在寻找一种简单的方法来并行执行少量 HTTP 请求,在那里我按照响应完成后发送它们的相同顺序返回响应,例如:

Using Perl, I'm looking for a simple way to perform a handful of HTTP requests in parallel, where I get responses back in the same order I sent them after they complete, e.g.:

my ($google, $perl) = foobar(GET => 'http://www.google.com/',
                             GET => 'http://www.perl.org/');

有我应该看的模块吗?

我知道我可以手工记账,但是在能够使用 做到这一点后,我感到被宠坏了jQuery 的 when 方法,我很想有一个使用 Perl 的简单解决方案.

I know I can do the bookkeeping by hand, but I feel spoiled after being able to do this using jQuery's when method, and I'd love to have as simple a solution using Perl.

感谢您的帮助.

推荐答案

use threads;
use LWP::UserAgent qw( );

my $ua = LWP::UserAgent->new();
my @threads;
for my $url ('http://www.google.com/', 'http://www.perl.org/') {
   push @threads, async { $ua->get($url) };
}

for my $thread (@threads) {
   my $response = $thread->join;
   ...
}

最好的部分是父级不会等待所有请求完成.完成正确的请求后,父级将解除阻止以处理它.

The best part is that the parent doesn't wait for all requests to be completed. As soon as the right request is completed, the parent will unblock to process it.

如果您使用了 Parallel::ForkManager 或其他无法等待特定孩子,您可以使用以下代码对结果进行排序:

If you used Parallel::ForkManager or something else where you can't wait for a specific child, you can use the following code to order the results:

for my $id (0..$#urls) {
   create_task($id, $urls[$id]);
}

my %responses;
for my $id (0..$#urls) {
   if (!exists($responses{$id})) {
      my ($id, $response) = wait_for_a_child_to_complete();
      $responses{$id} = $response;
      redo;
   }

   my $response = delete($responses{$id});
   ...
}

这篇关于如何在 Perl 中发出并行 HTTP 请求,并按顺序接收它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:48