在Mojolicious应用并行请求(Parallel requests in Mojoliciou

2019-09-03 06:44发布

我有Perl应用程序,其中,例如,平行于谷歌搜索:

use Mojo::UserAgent;
use Mojo::IOLoop;

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

my $delay = Mojo::IOLoop->delay(sub { say 'DONE1 (should be before render)'; });

foreach my $i ( 1 .. 10 ) {
    $delay->begin();

    $ua->get("http://www.google.ru/search?q=$i" => sub {
        say $i;
        $delay->end();
    });
}

$delay->wait() unless $delay->ioloop->is_running();

say 'DONE2 (should be before render)';
say 'Found! (render)';

而且它的正常工作:

6
1
7
10
3
9
2
5
8
4
DONE1 (should be before render)
DONE2 (should be before render)
Found! (render)

当我使用Mojolicious应用程序的代码中的控制器:

package MyApp::Google;

use Mojo::Base 'Mojolicious::Controller';

sub search {

    my $self = shift;

    my $delay = Mojo::IOLoop->delay(sub { $self->app->log->debug('DONE1 (should be before render)') });

    foreach my $i ( 1 .. 10 ) {
        $delay->begin();

        $self->ua->get("http://www.google.ru/search?q=$i" => sub {
            $self->app->log->debug($i);
            $delay->end();
        });
    }

    $delay->wait() unless $delay->ioloop->is_running();

    $self->app->log->debug('DONE2 (should be before render)');

    return $self->render_text('Found!');

}

这是要在一个错误的方式:

[Wed May 15 11:07:32 2013] [debug] Routing to controller "MyApp::Google" and action "search".
[Wed May 15 11:07:32 2013] [debug] DONE2 (should be before render)
[Wed May 15 11:07:32 2013] [debug] 200 OK (0.005689s, 175.778/s).
[Wed May 15 11:07:32 2013] [debug] 1
[Wed May 15 11:07:32 2013] [debug] 8
[Wed May 15 11:07:32 2013] [debug] 10
[Wed May 15 11:07:32 2013] [debug] 5
[Wed May 15 11:07:32 2013] [debug] 3
[Wed May 15 11:07:32 2013] [debug] 9
[Wed May 15 11:07:32 2013] [debug] 6
[Wed May 15 11:07:32 2013] [debug] 2
[Wed May 15 11:07:32 2013] [debug] 4
[Wed May 15 11:07:32 2013] [debug] 7
[Wed May 15 11:07:32 2013] [debug] DONE1 (should be before render)

我猜是这样$delay->wait() 不候 。 为什么要去?

Answer 1:

在这种情况下,你需要从控制器调用方法render_later禁用自动渲染。 ( http://mojolicio.us/perldoc/Mojolicious/Controller#render_later )

只需添加下一个要搜索的字符串控制器:

$self->render_later;

完整的例子:

#!/usr/bin/perl -wl
use Mojolicious::Lite;

get '/' => sub {
    my $self = shift;
    $self->render_later;
    my $delay = Mojo::IOLoop->delay(sub {
        $self->app->log->debug('Delay finished!');
        $self->render(text => 'test!');
    });
    for my $i (0 .. 5) {
        my $end = $delay->begin;
        Mojo::IOLoop->timer($i => sub {
            $self->app->log->debug($i);
            $end->();
        });
    }
};

app->start;


文章来源: Parallel requests in Mojolicious application