什么是 Redis Streams?
了解 Redis Streams 作为强大持久化消息队列的架构和优势
什么是 Redis Streams? 是 CoddyKit 上的免费 Redis Caching & Messaging (Pub/Sub, Streams) 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Redis Caching & Messaging (Pub/Sub, Streams) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Redis Caching & Messaging (Pub/Sub, Streams) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What are Redis Streams?
Welcome! In this lesson, we'll dive into Redis Streams, a powerful data structure for managing real-time event data.
Think of a stream as an append-only log of messages, similar to a traditional message queue or a Kafka topic, but built right into Redis.
Streams are ideal for building event-driven architectures, processing sensor data, or tracking user activity.
Streams vs. Pub/Sub
Redis already has Pub/Sub, so why Streams?
- Persistence: Stream messages are stored and not lost if consumers are offline. Pub/Sub messages are fire-and-forget.
- Consumer Groups: Streams support consumer groups for cooperative message processing, allowing multiple applications to read the same stream without duplicating work.
- Message History: You can read messages from any point in the stream's history.
Streams offer durability and advanced consumption patterns that Pub/Sub doesn't.
Stream Architecture: Entries & IDs
A Redis Stream is an ordered sequence of entries. Each entry is composed of:
- A unique Stream ID: This is a timestamp-based ID (e.g.,
1678886400000-0) that ensures messages are strictly ordered. - One or more field-value pairs: These are the actual data for the message, similar to a small Redis Hash.
Think of it as a log where each line has a unique timestamp and some key-value data.
Adding Entries with XADD
Producers add new entries to a stream using the XADD command. Redis automatically generates a unique ID for each new entry, or you can provide one.
The * wildcard tells Redis to generate a new, unique ID for the entry.
Try running this example:
public class Main {
public static void main(String[] args) {
System.out.println("Simulating Redis XADD command:");
String streamName = "sensor_data";
// XADD sensor_data * temp 25 hum 60
System.out.println("redisClient.xadd(");
System.out.println(" \"" + streamName + "\", \"*\",");
System.out.println(" \"temp\", \"25\", \"hum\", \"60\"");
System.out.println(");");
System.out.println("\nOutput (example ID): 1678886400000-0");
}
}Understanding Stream IDs
Stream IDs have two parts: <milliseconds-timestamp>-<sequence-number>.
- The timestamp is the time the entry was added (in Unix milliseconds).
- The sequence number is incremented if multiple entries are added within the same millisecond.
This structure guarantees that IDs are always increasing, providing a natural order for messages. You can use 0-0 to refer to the very beginning of a stream.
Reading from a Stream with XREAD
Consumers use the XREAD command to retrieve entries from one or more streams. You specify the stream name and the ID from which to start reading.
XREAD allows you to fetch a batch of messages, making it efficient for consumers.
Try running this example:
public class Main {
public static void main(String[] args) {
System.out.println("Simulating Redis XREAD command:");
String streamName = "sensor_data";
String startId = "0-0"; // Read from the beginning
// XREAD STREAMS sensor_data 0-0
System.out.println("List<Map<String, String>> entries =");
System.out.println(" redisClient.xread("STREAMS",");
System.out.println(" \"" + streamName + "\", \"" + startId + "\"");
System.out.println(");");
System.out.println("\nExample Output:");
System.out.println("ID: 1678886400000-0, {temp=25, hum=60}");
System.out.println("ID: 1678886400001-0, {temp=26, hum=61}");
}
}Blocking Reads for Real-time
To read new messages as they arrive, you can use the BLOCK option with XREAD. This makes the command wait for new data if no new entries are available.
You can also specify a timeout for the blocking operation. This is crucial for building real-time applications that react instantly to events.
Example: XREAD BLOCK 0 STREAMS mystream $ ($ means 'last ID in stream').
Stream Persistence & History
Unlike Pub/Sub, Redis Streams are persistent. Messages added to a stream remain there until explicitly removed or trimmed.
This allows new consumers to read the entire history of events from the beginning, or catch up from a specific point if they were temporarily offline.
This persistence is a key feature for reliable event logging and replay capabilities.
Ordered & Immutable Entries
Redis Streams guarantee that entries are always added in the order they are received and assigned strictly incrementing IDs.
Once an entry is added to a stream, it cannot be modified. This immutability is fundamental for maintaining an accurate, auditable log of events.
These properties make Streams excellent for event sourcing and ensuring data consistency.
Check Your Understanding
Which of the following are key benefits or characteristics of Redis Streams?
Recap: What are Redis Streams?
In this lesson, we learned that Redis Streams are a powerful, persistent, append-only log data structure.
- They offer persistence, ordered delivery, and support for consumer groups, differentiating them from Pub/Sub.
- We explored how to add entries with
XADDand read them withXREAD. - Streams are ideal for event sourcing, real-time data processing, and building reliable message queues.
Next, we'll dive deeper into Stream commands and features!
常见问题解答
「什么是 Redis Streams?」课时是免费的吗?
是的 — 「什么是 Redis Streams?」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Redis Caching & Messaging (Pub/Sub, Streams) 课程的其余内容,请升级到 CoddyKit PRO。 Redis Caching & Messaging (Pub/Sub, Streams) 课程共包含 4 节课。
「什么是 Redis Streams?」这节课中我会学到什么?
了解 Redis Streams 作为强大持久化消息队列的架构和优势 你通过在浏览器中直接运行的动手代码来练习 Redis Caching & Messaging (Pub/Sub, Streams),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Redis Caching & Messaging (Pub/Sub, Streams) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Redis Caching & Messaging (Pub/Sub, Streams) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「什么是 Redis Streams?」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Redis Caching & Messaging (Pub/Sub, Streams) 课中编写并运行代码吗?
能。每节 Redis Caching & Messaging (Pub/Sub, Streams) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。