Search code examples
goredisgo-redis

Unsubscribe from Redis doesn't seem to work


I am trying to use pub-sub in Redis. What I do is I open two redis-cli. The first one I issue the command flushall to make sure to start green.

Then in the other terminal I open the MONITOR to print all commands from my Golang sample client (code below).

Here's What I got printed from the MONITOR:

1590207069.340860 [0 127.0.0.1:58910] "smembers" "user:Ali:rooms"
1590207069.341380 [0 127.0.0.1:58910] "sadd" "user:Ali:rooms" "New"
1590207069.345266 [0 127.0.0.1:58910] "smembers" "user:Ali:rooms"
1590207069.353706 [0 127.0.0.1:58910] "sadd" "user:Ali:rooms" "Old"
1590207069.354219 [0 127.0.0.1:58912] "subscribe" "New"
1590207069.354741 [0 127.0.0.1:58910] "smembers" "user:Ali:rooms"
1590207069.355444 [0 127.0.0.1:58912] "unsubscribe" "New" "Old"
1590207069.356754 [0 127.0.0.1:58910] "sadd" "user:Ali:rooms" "OldPlusPlus"
1590207069.357206 [0 127.0.0.1:58914] "subscribe" "New" "Old"
1590207069.357656 [0 127.0.0.1:58910] "smembers" "user:Ali:rooms"
1590207069.358362 [0 127.0.0.1:58912] "unsubscribe" "OldPlusPlus" "New" "Old"
1590207069.361030 [0 127.0.0.1:58916] "subscribe" "OldPlusPlus" "New" "Old"

I am trying to make the client have one connection for all the channels that are being opened over time. Instead of a connection/thread to handle each channel to Redis. so whenever a new subscription request needed, I try to remove all previous subscriptions from the client and do a new subscription for the old channels plus the new channel.

But It seems that the unsubscribe command not working as expected (or I am missing something)!

Because from the first terminal when I try to get the number of clients for each channel:

127.0.0.1:6379> pubsub numsub OldPlusPlus New Old
1) "OldPlusPlus"
2) (integer) 1
3) "New"
4) (integer) 2
5) "Old"
6) (integer) 2

besides when I try to send a message to "New" channel, I got my go client receives the message twice!.

Here's the code that generates the above commands:

package main

import (
    "fmt"
    "github.com/go-redis/redis/v7"
    "log"
)


type user struct {
    name   string
    rooms  []string
    endSub chan bool
    sub    bool
}

func (u *user) connect(rdb *redis.Client) error {
    // get all user rooms (from DB) and start subscribe
    r, err := rdb.SMembers(fmt.Sprintf("user:%s:rooms", u.name)).Result()
    if err != nil {
        return err
    }
    u.rooms = r

    if len(u.rooms) == 0 {
        return nil
    }

    u.doSubscribe(rdb)

    return nil
}

func (u *user) subscribe(room string, rdb *redis.Client) error {
    // check if already subscribed
    for i := range u.rooms {
        if u.rooms[i] == room {
            return nil
        }
    }

    // add room to user
    userRooms := fmt.Sprintf("user:%s:rooms", u.name)
    if err := rdb.SAdd(userRooms, room).Err(); err != nil {
        return err
    }

    // get all user rooms (from DB) and start subscribe
    r, err := rdb.SMembers(userRooms).Result()
    if err != nil {
        return err
    }
    u.rooms = r

    if u.sub {
        u.endSub <- true
    }

    u.doSubscribe(rdb)

    return nil
}

func (u *user) doSubscribe(rdb *redis.Client) {
    sub := rdb.Subscribe(u.rooms...)
    go func() {
        u.sub = true
        fmt.Println("starting the listener for user:", u.name, "on rooms:", u.rooms)
        for {
            select {

            case msg, ok := <-sub.Channel():
                if !ok {
                    break
                }
                fmt.Println(msg.Payload)

            case <-u.endSub:
                fmt.Println("Stop listening for user:", u.name, "from rooms:", u.rooms)
                if err := sub.Unsubscribe(u.rooms...); err != nil {
                    fmt.Println("error unsubscribing")
                    return
                }
                break
            }
        }
    }()
}

func (u *user) unsubscribe(room string, rdb *redis.Client) error {
    return nil
}

var rdb *redis.Client

func main() {

    rdb = redis.NewClient(&redis.Options{Addr: "localhost:6379"})

    u := &user{
        name:   "Ali",
        endSub: make(chan bool),
    }

    if err := u.connect(rdb); err != nil {
        log.Fatal(err)
    }

    if err := u.subscribe("New", rdb); err != nil {
        log.Fatal(err)
    }

    if err := u.subscribe("Old", rdb); err != nil {
        log.Fatal(err)
    }

    if err := u.subscribe("OldPlusPlus", rdb); err != nil {
        log.Fatal(err)
    }

    select {}
}


Solution

  • The problem was related to the object of type *redis.PubSub that subscribes to the channel is not the one that used to unsubscribe from the channel.

    So I had to maintain a reference to such an object and then use that reference to unsubscribe of all channels.

    Here's the code modified and working:

    
    package main
    
    import (
        "fmt"
        "github.com/go-redis/redis/v7"
        "log"
    )
    
    type user struct {
        name        string
        rooms       []string
        stopRunning chan bool
        running     bool
        roomsPubsub map[string]*redis.PubSub
    }
    
    func (u *user) connect(rdb *redis.Client) error {
        // get all user rooms (from DB) and start subscribe
        r, err := rdb.SMembers(fmt.Sprintf("user:%s:rooms", u.name)).Result()
        if err != nil {
            return err
        }
        u.rooms = r
    
        if len(u.rooms) == 0 {
            return nil
        }
    
        u.doSubscribe("", rdb)
    
        return nil
    }
    
    func (u *user) subscribe(room string, rdb *redis.Client) error {
        // check if already subscribed
        for i := range u.rooms {
            if u.rooms[i] == room {
                return nil
            }
        }
    
        // add room to user
        userRooms := fmt.Sprintf("user:%s:rooms", u.name)
        if err := rdb.SAdd(userRooms, room).Err(); err != nil {
            return err
        }
    
        // get all user rooms (from DB) and start subscribe
        r, err := rdb.SMembers(userRooms).Result()
        if err != nil {
            return err
        }
        u.rooms = r
    
        if u.running {
            u.stopRunning <- true
        }
    
        u.doSubscribe(room, rdb)
    
        return nil
    }
    
    func (u *user) doSubscribe(room string, rdb *redis.Client) {
        pubSub := rdb.Subscribe(u.rooms...)
        if len(room) > 0 {
            u.roomsPubsub[room] = pubSub
        }
    
        go func() {
            u.running = true
            fmt.Println("starting the listener for user:", u.name, "on rooms:", u.rooms)
            for {
                select {
    
                case msg, ok := <-pubSub.Channel():
                    if !ok {
                        break
                    }
                    fmt.Println(msg.Payload, msg.Channel)
    
                case <-u.stopRunning:
                    fmt.Println("Stop listening for user:", u.name, "on old rooms")
    
                    for k, v := range u.roomsPubsub {
                        if err := v.Unsubscribe(); err != nil {
                            fmt.Println("unable to unsubscribe", err)
                        }
                        delete(u.roomsPubsub, k)
                    }
                    break
                }
            }
        }()
    }
    
    func (u *user) unsubscribe(room string, rdb *redis.Client) error {
        return nil
    }
    
    var rdb *redis.Client
    
    func main() {
    
        rdb = redis.NewClient(&redis.Options{Addr: "localhost:6379"})
    
        u := &user{
            name:        "Wael",
            stopRunning: make(chan bool),
            roomsPubsub: make(map[string]*redis.PubSub),
        }
    
        if err := u.connect(rdb); err != nil {
            log.Fatal(err)
        }
    
        if err := u.subscribe("New", rdb); err != nil {
            log.Fatal(err)
        }
    
        if err := u.subscribe("Old", rdb); err != nil {
            log.Fatal(err)
        }
    
        if err := u.subscribe("OldPlusPlus", rdb); err != nil {
            log.Fatal(err)
        }
    
        select {}
    }