Mojo :: UserAgent非阻塞与阻塞性能

时间:2018-09-09 22:45:22

标签: perl mojolicious mojo-useragent

我有以下代码:

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秒钟?

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

1 个答案:

答案 0 :(得分:1)

检查事情发生的第一件事。我无法得到同样的延迟。请记住,多次尝试每种方法以找出存在网络故障的异常值。请注意,非阻塞子程序的第二个参数是事务对象,通常写为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"; } ); }

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

一种可能性是保持活动状态保持打开连接。如果您将其关闭,会怎样?

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;

这是一个使用promises的版本,随着更多Mojo内容的迁移,您将习惯于该版本:

{{1}}