How to Get Real-Time Notifications for New Redis Set Elements Using Blocking Lists
This article explains how to receive immediate notifications when new items are added to a Redis set by leveraging a blocking list as a helper, avoiding polling and implementing a producer‑consumer pattern with atomic transactions.
Scenario
The task is to process new elements added to a Redis set immediately, without polling, by receiving a notification as soon as the set receives a new element.
Implementation
If a blocking command is available, the solution is straightforward, similar to the blocking BRPOP command for lists.
Blocking means the command waits when the key is empty and returns instantly when a new element appears. Non‑blocking commands return immediately.
The SPOP command for sets has no blocking version, but we can combine it with a blocking list. Use a helper list and BRPOP to achieve the desired behavior.
Producer adds an element to the set and pushes a dummy value onto the helper list inside a transaction to guarantee atomicity:
MULTI
SADD key element
LPUSH helper_key x
EXECConsumer blocks on the helper list with BRPOP. When the producer pushes to the list, the block is released, and the consumer can safely SPOP the set and process the element.
The helper list is only a signaling mechanism, not part of the business logic.
This pattern, demonstrated in the Redis documentation, cleverly creates a blocking‑style set using a blocking list.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
