Redis XREAD in PHP (Detailed Guide w/ Code Examples)
Use Case(s)
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.
Code Examples
Simple XREAD
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.
XREAD with Count and Block
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.
Best Practices
- Always handle connection failures. In production environments, your Redis instance may not always be available or reachable.
- Be cautious when using
BLOCK
option with a high value or without a timeout as it may lead to your application hanging. - Use meaningful stream keys. Stream keys should be descriptive enough for another developer to understand their purpose.
Common Mistakes
- Using XREAD without understanding that it's blocking. If no 'COUNT' option is provided, Redis will block until there are available items in the stream.
- Not connecting to the Redis server before trying to read from the stream. Always confirm that the Redis connection is active and working correctly.
FAQs
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.
Was this content helpful?
Similar Code Examples
Switch & save up to 80%
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost