Skip to content
yuki-kimoto edited this page Feb 10, 2012 · 3 revisions

Execute Non-blocking query in 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 applicaton 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;

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

Clone this wiki locally