In Redis, the BLMPOP
command is the blocking variant of LMPOP
.
Just like the LMPOP
command, BLMPOP
pops one or more elements from the first non-empty list key from the list of provided key names. However, unlike LMPOP
, if all lists are empty, BLMPOP
blocks the connection until another client pushes to it or until the timeout
(a double value specifying the maximum number of seconds to block) elapses.
The BLMPOP
command was introduced in Redis 7.0.0.
There’s also an BLPOP
command, which is the blocking variant of LPOP
.
Syntax
The syntax goes like this:
BLMPOP timeout numkeys key [key ...] LEFT | RIGHT [COUNT count]
Example
Suppose we create a list like this:
RPUSH scores 1 2 3 4 5 6 7 8 9 10
Result:
(integer) 10
Let’s look at its contents:
LRANGE scores 0 -1
Result:
1) "1" 2) "2" 3) "3" 4) "4" 5) "5" 6) "6" 7) "7" 8) "8" 9) "9" 10) "10"
Here’s an example of using the BLMPOP
command against that list and another list:
BLMPOP 0 2 emptylist scores LEFT COUNT 3
Result:
1) "scores" 2) 1) "1" 2) "2" 3) "3"
In this case, the emptylist
list was empty, and so BLMPOP
popped the first three elements from the scores
list. BLMPOP
pops elements only from the first non-empty list key. Seeing as the first list was empty, it popped the specified elements from the second list.
Let’s now use LRANGE
to return all remaining elements in the list:
LRANGE scores 0 -1
Result:
1) "4" 2) "5" 3) "6" 4) "7" 5) "8" 6) "9" 7) "10"
Empty Lists
As mentioned, BLMPOP
is the blocking variant of LMPOP
. Therefore, when all lists are empty, BLMPOP
blocks the connection until another client pushes to it or until the timeout
(a double value specifying the maximum number of seconds to block) elapses.
BLMPOP 5 2 emptylist anotheremptylist LEFT COUNT 3
Result:
(nil) (5.08s)
When I ran that example in my Redis client, there was a five second pause before the results were returned. That’s because both lists were empty, and so the connection was blocked until the timeout was reached.
Using a timeout of zero blocks the connection indefinitely.