Dragonfly Cloud is now available on the AWS Marketplace - Learn More

Redis XREADGROUP in PHP (Detailed Guide w/ Code Examples)

Use Case(s)

XREADGROUP is a Redis command used to read data from a stream with a specific consumer group. This is particularly useful in scenarios where you have multiple readers (consumers) for the same stream and want to ensure that every message is processed exactly once by any one of the consumers.

Code Examples

First, let's assume you have a Redis connection instantiated:

$redis = new Redis(); $redis->connect('127.0.0.1', 6379);

Now let's create a stream and a group:

// Create a Stream $redis->xAdd('mystream', '*', ['message' => 'Hello']); // Create a Group $redis->xGroup('CREATE', 'mystream', 'mygroup', 0, true);

Here's how to use XREADGROUP to read data from the stream:

$count = 1; // number of messages to retrieve $block = 2000; // block for 2000 milliseconds if no data available $streams = ['mystream' => '>']; // read all new messages in 'mystream' $result = $redis->xReadGroup('mygroup', 'consumer1', $streams, $count, $block); print_r($result);

In this example, we are using XREADGROUP to read one message ($count) from the stream 'mystream'. It'll block for 2 seconds ($block) if there's no new data available.

Best Practices

  1. Always specify a reasonable block time. A very long block time could potentially hold your application.
  2. Use the COUNT option sparingly and wisely; fetching too many messages at once could lead to high memory usage.

Common Mistakes

  1. Forgetting to set up consumer groups before trying to read from them.
  2. Not handling the case where XREADGROUP can return an empty array if there are no new messages in the stream.

FAQs

Q: What happens when two consumers read the same stream with XREADGROUP?

A: If two consumers belong to the same group, they will not receive the same messages from the stream. Redis ensures that each message is delivered to a single consumer in a group.

Q: What does the '>' symbol mean in the streams array?

A: The '>' symbol tells Redis to return new messages that the consumer hasn't seen yet. If you provide a message ID instead, it'll return messages with IDs greater than the provided one.

Was this content helpful?

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