Skip to content

Instantly share code, notes, and snippets.

@s1037989
Created December 25, 2013 00:00
Show Gist options
  • Save s1037989/8118946 to your computer and use it in GitHub Desktop.
Save s1037989/8118946 to your computer and use it in GitHub Desktop.
Sample blocking and non blocking options
#!/usr/bin/perl
use Mojolicious::Lite;
# This route is to emulate a slow web request
# This slow web request does not block; while it sleeps, it passes control
# back to the dispatcher for further request processing. Once the sleep
# completes, it then connects this back to the original request.
get '/:sleep' => {sleep => 0} => sub {
my $self = shift;
my $sleep = $self->param('sleep');
$self->app->log->info("Sleeping... $sleep");
$self->render_later; # Without this, slowsleep will be automatically rendered
Mojo::IOLoop->timer($sleep => sub {
$self->app->log->info("Slept: $sleep");
return $self->render(json=>{
ok => Mojo::JSON->true,
sleep => $sleep,
});
});
};
get '/blocking/:sleep' => {sleep => 0} => sub {
my $self = shift;
my $sleep = $self->param('sleep');
$self->ua->get($self->url_for("http://localhost:3001/$sleep"));
$self->render(text => "Slept for $sleep seconds. Blocked.");
};
get '/non-blocking/:sleep' => {sleep => 0} => sub {
my $self = shift;
my $sleep = $self->param('sleep');
$self->render_later;
$self->ua->get($self->url_for("http://localhost:3001/$sleep") => sub {
$self->render(text => "Slept for $sleep seconds. Didn't block.");
});
};
get '/' => 'index';
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment