0

我有以下代码:

my $ua = Mojo::UserAgent->new ();

my @ids = qw(id1 id2 id3);

foreach (@ids) {    
    my $input = $_;
    my $res = $ua->get('http://my_site/rest/id/'.$input.'.json' => sub {
        my ($ua, $res) = @_;
        print "$input =>" . $res->result->json('/net/id/desc'), "\n";
    });    
}

Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

为什么当我运行上面的代码(非阻塞)时,在运行代码作为阻塞时需要大约 6 秒,即在循环内部类似于:

 my $res = $ua->get('http://my_site/rest/id/'.$input.'.json');
 print "$input =>" . $res->result->json('/net/id/desc'), "\n";

没有最新的线路大约需要 1 秒?

为什么阻塞代码比非阻塞代码快?

4

1 回答 1

1

首先要检查事情何时发生。我不能得到同样的延迟。请记住多次尝试每种方式以发现存在网络故障的异常值。请注意,非阻塞子的第二个参数是一个事务对象,通常写为$tx,其中响应对象通常写为res

use Mojo::Util qw(steady_time);

say "Begin: " . steady_time();
END { say "End: " . steady_time() }

my $ua = Mojo::UserAgent->new ();

my @ids = qw(id1 id2 id3);

foreach (@ids) {
    my $input = $_;
    my $res = $ua->get(
        $url =>
        sub {
            my ($ua, $tx) = @_;
            print "Fetched\n";
            }
        );
    }

一种可能性是 keep-alive 保持一个开放的连接。如果你把它关掉会发生什么?

    my $res = $ua->get(
        $url =>
        { Connection => 'close' }
        sub {
            my ($ua, $tx) = @_;
            print "Fetched\n";
            }
        );

这是一个使用promises的版本,随着更多 Mojo 的东西移到它上面,你会想要习惯它:

use feature qw(signatures);
no warnings qw(experimental::signatures);

use Mojo::Promise;
use Mojo::Util qw(steady_time);
use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;

say "Begin: " . steady_time();
END { say "End: " . steady_time() }

my @ids = qw(id1 id2 id3);

my @gets = map {
    $ua->get_p( 'http://www.perl.com' )->then(
        sub ( $tx ) { say "Fetched: " . steady_time() },
        sub { print "Error: @_" }
        );
    } @ids;

Mojo::Promise->all( @gets )->wait;
于 2018-09-10T00:43:09.103 回答