Search code examples
perlredismojolicious

Can't get Mojo::Redis2 to subscribe


I wrote the following program (redis.pl), Redis is running locally with the default port settings, but when I run redis.pl with morbo redis.pl I never get ********* 1 on the screen. Why is that? It seems the subscription never happens. How can I fix this?

#!/usr/bin/perl

use v5.18;
use warnings;

use Mojolicious::Lite;
use Mojo::Redis2;

say "Welcome";

my $redis = Mojo::Redis2->new();

$redis->subscribe(['pubsub'] => sub {
    say "********* 1";
});

get '/' => sub {
    my $self = shift;

    $self->render(json => {a => 1});
};

app->start;

Solution

  • I don't have a redis instance installed currently, but I think this should work.

    #!/usr/bin/perl
    
    use v5.18;
    use warnings;
    
    use Mojolicious::Lite;
    use Mojo::Redis2;
    
    say "Welcome";
    
    helper redis => sub {state $redis = Mojo::Redis2->new()};
    
    app->redis->subscribe(['pubsub'] => sub {
        say "********* 1";
    });
    
    get '/' => sub {
        my $self = shift;
    
        $self->render(json => {a => 1});
    };
    
    app->start;
    

    I suspect that once the redis instance goes out of scope, you lose it and its connections.