The XGROUP
command in Redis is used to manage consumer groups within a stream. It's ideal for use cases where you need to distribute the processing of data across different consumers. This is common in distributed systems where load balancing and failure tolerance are critical.
We'll be using the Go go-redis/redis
package for our examples. Ensure it's installed by running go get github.com/go-redis/redis
.
package main import ( "fmt" "github.com/go-redis/redis/v8" "context" ) var ctx = context.Background() func main() { rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) err := rdb.XGroupCreateMkStream(ctx, "mystream", "mygroup", "$").Err() if err != nil { panic(err) } fmt.Println("Consumer group created successfully.") }
In this example, we connect to our Redis instance and use the XGroupCreateMkStream
function to create a new consumer group named mygroup
on the mystream
stream. The $
guarantees that only new messages will be delivered to consumers of this group.
XGROUP CREATE
command. If the consumer group already exists, an error will be returned.$
or 0-0
) when creating a consumer group - whether you want to process only new messages or all existing and future messages.MKSTREAM
option will result in an error. If you're not sure whether the stream exists, use XGroupCreateMkStream
.What does the $
mean in XGROUP CREATE
command?
The $
is an ID which represents the latest ID in the stream. It means that the consumer group will only receive new messages that are added to the stream after the creation of the group.
Can I add a consumer to a group directly?
No, consumers are not added directly to a group. When a consumer reads from a group using XREADGROUP
, it gets associated with that group.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.