【问题标题】:Mojo::UserAgent non-blocking vs blocking performanceMojo::UserAgent 非阻塞 vs 阻塞性能
【发布时间】:2018-09-09 22:45:22
【问题描述】:

我有以下代码:

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

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

【问题讨论】:

  • 我重温了这个问题

标签: perl mojolicious mojo-useragent


【解决方案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-05-29
    • 2013-10-15
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    相关资源
    最近更新 更多