I’ve been learning and implementing Redis streams for the past few days to set up a real-time communication system and queue management for our product LiveAPI, an auto API doc generation tool.
In this article, let us discuss a few Redis Stream commands that you need to be aware of while building efficient solutions using Redis Streams.
- XADD: This command helps to add new entries to a stream.
Example:
XADD mystream * sensor-id 1234 temperature 19.8 humidity 43.5
This command adds a new entry to the stream 'mystream'. The * tells Redis to auto-generate the entry ID. Each entry contains multiple field-value pairs (sensor-id, temperature, humidity).
2.XREAD: This command reads entries from one or more streams.
Example: XREAD COUNT 2 STREAMS mystream 0
This reads 2 entries from 'mystream' starting from the beginning (ID 0).
3.XRANGE: This command returns entries within a specific ID range.
Example: XRANGE mystream 1641293000000-0 1641293060000-0
This command is used to get historical data within a specific range.
4.XGROUP CREATE: Creates a consumer group for stream processing.
Example: XGROUP CREATE mystream mygroup $
Creates a consumer group named 'mygroup' for 'mystream'. The $ means the group will only read new messages (from the last ID).
5.XREADGROUP: Reads from a stream as part of a consumer group.
Example: XREADGROUP GROUP mygroup consumer1 COUNT 1 STREAMS mystream >
This reads one unread message from 'mystream' as consumer1 in mygroup. The > means "give me new messages that haven’t been delivered to other consumers".
6.XCLAIM: Used to transfer ownership of pending messages.
Example: XCLAIM mystream mygroup consumer2 30000 1692312456878-0
This command will transfer ownership from one consumer to another within the same consumer group. This is particularly useful in handling failed consumers or rebalancing workloads. XCLAIM ensures no messages are lost if a consumer fails, enables work redistribution for better load balancing, and provides message recovery mechanisms.
I hope these few commands help to give you an idea about Redis streams and their commands. Share your valuable feedback.
Top comments (0)