Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis publishing when no subscriber

In Redis pub/sub if something is published when there is no subscriber, data is kind of lost.

What i wanted is kind of notification to publisher when subscriber is subscribed.

One way could be keep publishing in a loop and break the loop when publisher find at least one subscriber. But i don't think thats a good way. (Also i can't keep exponential back off).

while(1) {
    $numOfSubscriber = $redis->publish($channel1, $encodePublish);
    if($numOfSubscriber > 0)
        break;
}

Is there any better way to solve the same issue?

I am using Predis.

like image 602
amitchhajer Avatar asked Jan 16 '23 20:01

amitchhajer


1 Answers

It's hard to be specific unless you explain more about your usecase, but if it's enough that one subscriber gets any message, you could implement a queue using a redis list and store all messages there, while also publishing. Pseudo-code:

Publisher:

# Persist message in a queue
lpush channel1.queue message
# Publish message to any connected subscriber
publish channel1 message

Subscriber:

# Subscribe to channel1
subscribe channel1
# Process any persisted messages
brpop channel1.queue

Edit: Another solution, where publisher only stores messages if there was no subscriber:

Publisher:

subscribers = publish channel1 message
if subscribers == 0
  lpush channel1.queue message

Subscriber:

# handle stored messages
while(message = rpop channel1.queue)
  # process message

# subscribe for new messages
subscribe channel1
like image 193
Linus Thiel Avatar answered Jan 21 '23 17:01

Linus Thiel