Richard Bucker

Mojolicious plus Redis equals RestMQ-pl

Posted at — Nov 2, 2011

I’m playing with Mojolicious. One of the fun projects I want to implement is a perl version of RestMQ. It was the main reason that I used then I requested a CPAN id. One of my previous complaints was, and remains, that the Python and Ruby versions of this project look elegant and fun. (this also means that a lot of the code is hidden in either the framework or the language; which I hate).I’ll be posting and submitting this project eventually, however, in the meantime I had not been able to get things working properly. There was a timing issue with MojoX::Redis and Mojo. It was not working well at all. I read and read all of the docs over and over again. In fact I had abandoned MojoX::Redis altogether in order to try AnyEvent::Redis. (it also failed).Finally I reread a page in minute detail. The first piece of example code looked more like a standalone snippet. Which did not make any sense in this context because it was supposed to be a MojoX::Redis implementation in Mojolicious. (The wiki has been wrong more than once before)But then; there it was:If you are planning to use MojoX::Redis in Mojolicious' daemon mode, create MojoX::Redis instance with¬†ioloop¬†attr:my $redis = MojoX::Redis->new(ioloop => Mojo::IOLoop->new);Once I add this to my code and then added the stop and start calls to my function:post ‘/q/:queue’ => sub { my $self = shift; my $result = undef; my $queue = $self->param(‘queue’); my $value = $self->param(‘value’); if (! defined $queue) { $self->app->log->debug(‘queue was not in the URL (’.$queue.')'); $self->render_not_found; } else { my $uuid = undef; my $lkey = undef; my $q1 = $queue . $QUEUE_SUFFIX; my $q2 = $queue . $UUID_SUFFIX; $redis->incr($q2 => sub{ my ($redis, $res) = @_; $uuid = $res->[0]; $redis->ioloop->stop; })->start; $self->app->log->debug(‘the uuid is (’.($uuid||‘undefined’).')'); $lkey = $queue . ‘:’ . $uuid; $redis->execute(“sadd” => [$QUEUESET, $q1]); $redis->execute(“set” => [$lkey, $value]); $redis->execute(“lpush” => [$q1, $lkey]); $self->app->log->debug(‘the uuid q is (’.($q2||‘undefined’).')'); $self->render(text => ‘{ok, ' . $lkey . ‘}'); }};it worked great. I still do not think this code is sexy and it’s no where near the appearance of the Python or Ruby code(I should probably remove the debug statements). But it works… and it seems to be pretty fast too.