Browse Source

rewrote app.psgi. Do not use Plack::Builder and Plack::Response, use $dbi->selectrow_arrayref for more performance

Masahiro Nagano 11 years ago
parent
commit
f6498ec79e
1 changed files with 22 additions and 14 deletions
  1. 22 14
      plack/app.psgi

+ 22 - 14
plack/app.psgi

@@ -1,24 +1,32 @@
+use strict;
 use v5.16;
-use Plack::Builder;
-use Plack::Request;
-use JSON::XS 'encode_json';
+use utf8;
+use JSON::XS qw(encode_json);
 use DBI;
 
 my $dbh = DBI->connect_cached(
     'dbi:mysql:database=hello_world;host=localhost;port=3306', 
-    qw(benchmarkdbuser benchmarkdbpass)
+    'benchmarkdbuser',
+    'benchmarkdbpass',
+    { AutoInactiveDestroy => 1, mysql_enable_utf8 => 1 }
 ) || die $!;
 
-my $sth = $dbh->prepare_cached('SELECT randomNumber FROM World WHERE id = ?');
+my $query = 'SELECT id, randomNumber FROM World WHERE id = ?';
 my $header = [qw(Content-Type application/json)];
 
-builder {
-    mount '/json' => sub { [ 200, $header, [ encode_json({ message => 'Hello, World!' })] ] },
-    mount '/db' => sub {
-        my @rs = map { id => $_->[0] + 0, randomNumber => $_->[1] },
-            grep exists $_->[1],
-            map [$_, $sth->execute($_) && $sth->fetchrow_array],
-            map int rand 10000 + 1,
-            1..Plack::Request->new(shift)->param('queries')//1;
-        [ 200, $header, [ encode_json( @rs > 1 ? \@rs : $rs[0] ) ] ] } };
+my $app = sub {
+    my $env = shift;
+    if ( $env->{PATH_INFO} eq '/json' ) {
+        return [ 200, $header, [ encode_json({ message => 'Hello, World!' }) ]];
+    }
+    elsif ( $env->{PATH_INFO} eq '/db' ) {
+        my ($n) = ($env->{QUERY_STRING} || "" ) =~ m!queries=(\d+)!;
+        $n //= 1;
+        my @rs = map {{id=>$_->[0]+0,randomNumber=>$_->[1]+0}} 
+            map { $dbh->selectrow_arrayref($query,{},int rand 10000 + 1) } 1..$n;
+        return [ 200, $header, [ encode_json( @rs > 1 ? \@rs : $rs[0] ) ]];
+    }
+    [ 404, [], ['not found']];
+};
 
+$app;