The XGROUP
command in Redis is typically used for managing consumer groups in the context of stream data structures. The most common use cases include:
Let's assume we're dealing with a chat application, and we want to create a consumer group for each channel. Here's how you can do it in Ruby using the redis gem.
First, we need to establish a connection with Redis.
require 'redis' redis = Redis.new(host: "localhost", port: 6379)
# Let's say we have a stream "chat:1" (representing chat channel 1) stream_key = "chat:1" group_name = "group1" # We create a new consumer group associated with the stream redis.xgroup(:create, stream_key, group_name, '$', mkstream: true)
In this example, '$'
represents the latest message in the stream. When a new consumer joins this group, they will start receiving messages which were added to the stream after the group was created. mkstream: true
option means it will create the stream if it doesn't exist.
last_delivered_id = "1526985755631-0" redis.xgroup(:setid, stream_key, group_name, last_delivered_id)
This sets the last delivered ID to the specified value, meaning that consumers will receive messages with IDs greater than this.
Q: Can I use XGROUP command on non-stream keys?
A: No, XGROUP
command only applies to stream data structures. Using it on non-stream keys will result in an error.
Q: What happens if I don't provide the mkstream option when creating a group?
A: If the stream doesn't exist and mkstream
option is not provided, Redis will return an error.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.