Redis: Streams
A Redis stream is a data structure that acts like an append-only log but also implements several operations to overcome some of the limits of a typical append-only log. We can use streams to record and simultaneously syndicate events in real time.
Redis generates a unique ID for each stream entry.
Streams keep messages in Redis for as long as you want (configurable).
Consumers can read at their own pace, even if they were offline.
We can acknowledge messages (
XACK
) and track delivery.
Similar like pub/sub we need A producer and consumers to implement redis streams in our system.
Basic Example
Lets create a basic example of redis streams using XADD
and XREAD
command.
Setup
To run redis server you can install it directly in your machine or using virtualization. For me I prefer to use docker and here is how to do it.
Run a detached container with name my-redis
using latest redis
image and expose the port 6379
.
Run redis-cli
inside the newly created redis container.
XADD
XADD
This is the simplest form of adding a message to a Redis Stream. Each message will have a unique ID and some data fields.
mystream
: name of the stream, redis will create the stream if not exist.*
: Stream ID, will auto-generate a unique ID if the ID argument specified is the*
.message Hello
: Key value pair data,message
is the key and value isHello
.
XREAD
XREAD
Read data from one or multiple streams. This command has an option to block if items are not available.
COUNT 1
: Return maximum 1 element for each stream.STREAMS mystream 0
:mystream
: Name of the stream.0
: Read element from the start.
References
Last updated