perl - Parallel requests in Mojolicious application -
i have perl application which, example, parallel searching in google:
use mojo::useragent; use mojo::ioloop; $ua = mojo::useragent->new(); $delay = mojo::ioloop->delay(sub { 'done1 (should before render)'; }); foreach $i ( 1 .. 10 ) { $delay->begin(); $ua->get("http://www.google.ru/search?q=$i" => sub { $i; $delay->end(); }); } $delay->wait() unless $delay->ioloop->is_running(); 'done2 (should before render)'; 'found! (render)';
and it's works fine:
6 1 7 10 3 9 2 5 8 4 done1 (should before render) done2 (should before render) found! (render)
when use code in mojolicious application in controller:
package myapp::google; use mojo::base 'mojolicious::controller'; sub search { $self = shift; $delay = mojo::ioloop->delay(sub { $self->app->log->debug('done1 (should before render)') }); foreach $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 before render)'); return $self->render_text('found!'); }
it going in wrong way:
[wed may 15 11:07:32 2013] [debug] routing controller "myapp::google" , action "search". [wed may 15 11:07:32 2013] [debug] done2 (should 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 before render)
i guess $delay->wait()
is not waiting. why going?
in case need disable automatic rendering calling method render_later controller. (http://mojolicio.us/perldoc/mojolicious/controller#render_later)
just add next string search controller:
$self->render_later;
complete example:
#!/usr/bin/perl -wl use mojolicious::lite; '/' => sub { $self = shift; $self->render_later; $delay = mojo::ioloop->delay(sub { $self->app->log->debug('delay finished!'); $self->render(text => 'test!'); }); $i (0 .. 5) { $end = $delay->begin; mojo::ioloop->timer($i => sub { $self->app->log->debug($i); $end->(); }); } }; app->start;
Comments
Post a Comment