app.pl 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/env perl
  2. use Web::Simple;
  3. use JSON::XS;
  4. use DBI;
  5. my $dsn = "dbi:mysql:database=hello_world;host=localhost";
  6. my $dbh = DBI->connect( $dsn, 'benchmarkdbuser', 'benchmarkdbpass', { RaiseError => 1 });
  7. my $sth = $dbh->prepare('SELECT * FROM World where id = ?');
  8. sub dispatch_request {
  9. sub (/json) {
  10. [ 200, [ 'Content-type' => 'application/json', ],
  11. [ encode_json({ message => 'Hello, World!' }) ] ];
  12. },
  13. sub (/db) {
  14. my $id = int(rand 10000) + 1;
  15. my $rand;
  16. $sth->execute($id);
  17. $sth->bind_col(2, \$rand);
  18. if ( my @row = $sth->fetch ) {
  19. [ 200, [ 'Content-type' => 'application/json', ], [ encode_json({ id => $id, randomNumber => $rand })] ];
  20. }
  21. },
  22. sub (/query + ?queries~) {
  23. my ($self, $queries) = @_;
  24. $queries //= 1;
  25. $queries = 1 if ( $queries !~ /^\d+$/ || $queries < 1 );
  26. $queries = 500 if $queries > 500;
  27. my $rand;
  28. my @response;
  29. if ($queries == 1) {
  30. my $id = int(rand 10000) + 1;
  31. $sth->execute($id);
  32. $sth->bind_col(2, \$rand);
  33. if ( my @row = $sth->fetch ) {
  34. [ 200, [ 'Content-type' => 'application/json', ],
  35. [ encode_json([{ id => $id, randomNumber => $rand }])] ];
  36. }
  37. }
  38. else {
  39. for ( 1 .. $queries ) {
  40. my $id = int(rand 10000) + 1;
  41. $sth->execute($id);
  42. $sth->bind_col(2, \$rand);
  43. if ( my @row = $sth->fetch ) {
  44. push @response, { id => $id, randomNumber => $rand };
  45. }
  46. }
  47. [ 200, [ 'Content-type' => 'application/json', ], [ encode_json(\@response)] ];
  48. }
  49. }
  50. }
  51. __PACKAGE__->run_if_script;