miyagawa / AnyEvent-Redis

Asynchronous Redis client
http://search.cpan.org/dist/AnyEvent-Redis
41 stars 16 forks source link

Subscribe problem #24

Open dant4z opened 10 years ago

dant4z commented 10 years ago

Hi, i'm using AnyEvent::Redis with the Net::WebSocket::Server module like this:

use Net::WebSocket::Server; use AnyEvent::Redis;

Net::WebSocket::Server->new(
    listen => 8080,
    on_connect => sub {
        my ($serv, $conn) = @_;
        my $redis = AnyEvent::Redis->new(
            host => '127.0.0.1',
            port => 6379,
            encoding => 'utf8',
            on_error => sub { warn @_ },
            on_cleanup => sub { warn "Connection closed: @_" },
        );
        $conn->on(
            ready => sub {
                my ($conn) = @_;
                $redis->subscribe("test", sub {
                    my ($message, $channel) = @_;
                    $conn->send_utf8($message);
                });
            },
            utf8 => sub {
                my ($conn, $msg) = @_;
                warn $msg;
                $conn->send_utf8($msg);
            },
        );
    },
)->start;

But when I start this script and connect to his websocket, i see that this connection to redis is established, but not subscribed:

addr=127.0.0.1:54669 fd=6 name= age=2 idle=2 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=0 omem=0 events=r cmd=NULL

What i doing wrong? please help me.

Thanks.

Yenya commented 3 years ago

Hello,

I have a similar problem - trying to use AnyEvent::Redis inside Twiggy (AnyEvent-based HTTP server). I try to subscribe to some topics before entering the server event loop, but I don't receive any events at all, unless I call $cv->recv ($cv being the object returned from $redis->subscribe). But calling $cv->recv blocks the whole process, making it unusable inside the event-based HTTP server.

@dant4z - maybe you can try to do $redis->subscribe(...)->recv and verify that you can receive the events (altough I guess your process would be blocked inside the ->ready() function then).

EDIT: Nevermind, my problem was in unexpectedly short lifecycle of $redis in my code - it got destroyed too early, so naturally I did not get any events after that. One possible fix was s/my $redis/our $redis/. Anyway, mind the scopes of your objects.