Home > front end >  Is there a way to allow multiple connections to Dancer2
Is there a way to allow multiple connections to Dancer2

Time:04-21

My program:

#!/usr/bin/perl

use strict;
use warnings;
use Dancer2;

$| = 1;

set host => '127.0.0.1';
set port => 7071;

get '/foo' => sub {
    `sleep 5`;
    'ok'
};

start;

Then I am run the following for loop:

for i in $(seq 1 3)
> do
>   time curl http://localhost:7071/foo &
> done

Output:

ok
real    0m5.032s
user    0m0.013s
sys     0m0.000s
ok
real    0m10.037s
user    0m0.012s
sys     0m0.000s
ok
real    0m15.043s
user    0m0.004s
sys     0m0.008s

It seems to Dancer2 can only accept one request one time, how to allow multiple connections to Dancer2?

CodePudding user response:

Perl programs are generally single-threaded. If you want to handle multiple things at the same time, you need to manage that explicitly.

  • You can run multiple instances of your Dancer app. When one instance is busy, the other instances can still handle requests. Some servers automatically support such “pre-forking”, for example Starman. This is the classic solution to your problem, coupled with the observation that your backend shouldn't do lots of stuff that block execution.

  • You can explicitly write your app to work asynchronously. Your sleep invocation is blocking the entire process, but you could also use libraries that let you resume handling of a request when some event occurs. For example, the Dancer2 docs show examples for using the AnyEvent timers.

If you are familiar with the Express web framework in JavaScript, it generally uses the second approach: NodeJS doesn't let you block the process by sleeping, and instead requires you to use promises (async/await) or callbacks to explicitly account for asynchronous execution.

CodePudding user response:

Last time I setup a dancer app, used plackup and Starman so a PSGI interface is provided.

cd $APP_DIR    
$PLACKUP -E $ENV -s Starman  --workers=20 -p 9000 \
                     -a bin/app.pl 2>&1 >  $LOGFILE &

There is a reverse proxy in front of the perl to handle static files faster and provide some anti-cracking protections in more commonly used tools for the Perl-deficient.

simbabque's answer is better. It shows this and other options.

  • Related