Effect of duplicate Redis subscription to same channel name

I am making an assumption that your question is targeted at the Redis API itself. Please let me know if it isn't.

The answer is also based on the assumption that you are using a single redis client connection.

The pubsub map is a hashtable.

To answer your question: If you subscribe multiple times with the same string, you will continue to have only one subscription(you can see that the subscribe happens based on the hashtable here: https://github.com/antirez/redis/blob/3.2.6/src/pubsub.c#L64.

Conversely, calling a single unsubscribe will unsubscribe your other subscriptions for that channel/pattern as well.

If it helps, here is a simple example in Go (I have used the go-redis library) that illustrates the unsubscribe and hashtable storage parts of the answer.

package main

import (
    "fmt"
    "log"
    "time"

    "github.com/go-redis/redis"
)

func main() {
    cl := redis.NewClient((&redis.Options{
        Addr:     "127.0.0.1:6379",
        PoolSize: 1,
    }))

    ps := cl.Subscribe()

    err := ps.Subscribe("testchannel")
    if err != nil {
        log.Fatal(err)
    }

    err = ps.Subscribe("testchannel")
    if err != nil {
        log.Fatal(err)
    }

    err = ps.Unsubscribe("testchannel")
    if err != nil {
        log.Fatal(err)
    }

    go func() {
        msg, err := ps.ReceiveMessage()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(msg.Payload)
    }()

    err = cl.Publish("testchannel", "some value").Err()
    if err != nil {
        log.Fatal(err)
    }

    time.Sleep(10 * time.Second)
}

Tags:

Redis