The XREAD
command in Redis is used when working with streams. It allows you to read data from one or multiple streams, where every entry has a unique ID. In PHP Redis, this can be utilised for various real-time applications such as chat systems, data ingestion pipelines, activity tracking and more.
Reading from a single stream with the $stream
key and 0
as the ID.
$redis = new Redis(); $redis->connect('127.0.0.1', 6379); $result = $redis->xRead(['stream' => 0]); print_r($result);
This code connects to the local Redis server, reads from the 'stream' starting at ID '0', then prints the result.
Reading with COUNT
gives a maximum number of elements returned, while BLOCK
specifies the maximum waiting time.
$redis = new Redis(); $redis->connect('127.0.0.1', 6379); $options = [ 'count' => 100, 'block' => 2000, ]; $result = $redis->xRead(['stream' => '$'], $options); print_r($result);
Here, we're reading from the 'stream' starting at the latest entry ($
). We also specify to return at most 100 elements and wait for at most 2000 milliseconds.
BLOCK
option with a high value or without a timeout as it may lead to your application hanging.Q: What does the $
symbol mean when reading from a stream?
A: In Redis streams, $
represents the ID of the latest message in the stream. This is useful when you want to start reading only new messages that arrive after you run the command.
Q: What happens if I use XREAD
on an empty stream?
A: By default, XREAD
will block until some data is available. However, you can control this using the 'BLOCK' option in the command.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.