0Pricing
Redis Caching & Messaging (Pub/Sub, Streams) · Lezione

Cosa sono gli Stream di Redis?

Comprenda l’architettura e i vantaggi degli Stream di Redis come potente coda di messaggi persistente.

Cosa sono gli Stream di Redis? è una lezione Redis Caching & Messaging (Pub/Sub, Streams) gratuita su CoddyKit. Questa è la lezione 1 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Redis Caching & Messaging (Pub/Sub, Streams), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Redis Caching & Messaging (Pub/Sub, Streams) include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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 XADD and read them with XREAD.
  • 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!

Domande Frequenti

La lezione «Cosa sono gli Stream di Redis?» è gratuita?

Sì — il testo completo di «Cosa sono gli Stream di Redis?» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Redis Caching & Messaging (Pub/Sub, Streams), passa a CoddyKit PRO. Il corso Redis Caching & Messaging (Pub/Sub, Streams) include 4 lezioni in totale.

Cosa imparerò in «Cosa sono gli Stream di Redis?»?

Comprenda l’architettura e i vantaggi degli Stream di Redis come potente coda di messaggi persistente. Eserciti Redis Caching & Messaging (Pub/Sub, Streams) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Redis Caching & Messaging (Pub/Sub, Streams)?

Non è richiesta alcuna esperienza precedente. Redis Caching & Messaging (Pub/Sub, Streams) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 1 di 4.

Quanto tempo richiede la lezione «Cosa sono gli Stream di Redis?»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Redis Caching & Messaging (Pub/Sub, Streams)?

Sì. Ogni lezione Redis Caching & Messaging (Pub/Sub, Streams) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Cosa sono gli Stream di Redis?
  2. Strutture dati e comandi degli Stream
  3. Persistenza dei messaggi negli Stream
  4. Limitare e ridurre gli stream
← Torna a Redis Caching & Messaging (Pub/Sub, Streams)