go-redis
go-redis copied to clipboard
PubSub documentation example unclear on concurrent use
The following example exist in the docs: https://godoc.org/github.com/go-redis/redis#ex-PubSub
- pubsub := rdb.Subscribe("mychannel1")
- // Wait for confirmation that subscription is created before publishing anything.
- _, err := pubsub.Receive()
- if err != nil {
-
panic(err) - }
- // Go channel which receives messages.
- ch := pubsub.Channel()
- // Publish a message.
- err = rdb.Publish("mychannel1", "hello").Err()
- if err != nil {
-
panic(err) - }
- time.AfterFunc(time.Second, func() {
-
// When pubsub is closed channel is closed too. -
_ = pubsub.Close() - })
- // Consume messages.
- for msg := range ch {
-
fmt.Println(msg.Channel, msg.Payload) - }
Based on the documentation it seems that:
- code between lines 1-8 are not safe for concurrent use.
- code between line 10 is safe for concurrent use.
I am struggling to determine the correct setup for an app that has long lived connections, where each connection could be subscribed to the same topic, for example topicfoobar or each connection has it's own topic.
In my example I can have multiple consumers that all need a copy of the message from the producer.
It is possible to update the documentation or provide an example how to handle multiple consumers for dynamic topics.
+1 I am using a global redis Client and I launch a number of goroutines that each "psubscribe" to a different key, i.e. each goroutine has a snippet of this form : ` PubSub := redisClient.PSubscribe(ctx, keys...)
msgi, err := PubSub.Receive(context.Background())
... do something with msgi ... `
I am confused if this is safe for concurrent use or if this is indeed the case the documentation of Psubscribe is referring to ("not safe for use by multiple goroutines").
This issue is marked stale. It will be closed in 30 days if it is not updated.