Dragonfly

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

Common Mistakes

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

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

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