gpt4 book ai didi

perl - Mojolicious 应用程序中的并行请求

转载 作者:行者123 更新时间:2023-12-01 11:44:36 26 4
gpt4 key购买 nike

我有 perl 应用程序,例如,在 google 中进行并行搜索:

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)

当我在 Controller 的 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() 不是在等待。为什么会这样?

最佳答案

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

只需将下一个字符串添加到search Controller :

$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;

关于perl - Mojolicious 应用程序中的并行请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16558940/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com