Skip to content
Peter Scott edited this page Mar 27, 2017 · 1 revision

Execute Non-blocking query in MySQL

Using Mojo::mysql

See alsoMojo::mysql|mojolicio.us/perldoc/Mojo/mysql

Using DBIx::Custom

Mojolicious have non-blocking IO loop. but MySQL is blocked when query is executed, so whole application is blocked.

DBIx::Custom have simple solution using Any::Event and EV. This is Mojolicious::Lite application example.

  use Mojolicious::Lite;
  use EV;
  use DBIx::Custom;

  my $dbi = DBIx::Custom->connect(
    dsn => 'dbi:mysql:database=usertest',
    user => 'root'
  );

  $dbi->async_conf({
    prepare_attr => {async => 1},
    fh => sub { shift->dbh->mysql_fd }
  });

  get '/' => sub {
    my $self = shift;
    
    $self->render_later;
    $dbi->select('SLEEP(5), 3', async => sub {
      my ($dbi, $result) = @_;
      my $row = $result->fetch_one;
      $self->render(text => $row->[1]);
    });
  };

  app->start;

sleep 5 second on database server, but application is not blocked.