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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With