Lesson 1
Introduction to Redis Streams
Introduction to Redis Streams

Welcome back! In this lesson, we will explore Redis Streams — a powerful feature used for processing streams of data. Using PHP, this lesson will guide you through the basics and demonstrate how Redis Streams can be essential for high-performance applications. You'll learn how to create streams, add events to them, and read events from them.

Streams in Redis are data structures that follow the FIFO (First In, First Out) principle. Each entry in a stream is stored with a unique ID, which by default includes the current timestamp, but can be customized when adding events. For example, an entry might have the ID 1700000000000-1. 1700000000000 is the timestamp, while 1 is the sequence number. If two messages are added at the same exact millisecond, Redis will automatically increment the sequence number to maintain uniqueness, resulting in IDs like 1700000000000-2. When you add an entry to a Redis Stream using the XADD command, Redis returns the unique ID of the newly added entry.

Streams can efficiently handle continuous flows of data, making them ideal for use cases like chat applications, monitoring systems, or user activity tracking.

Redis Streams are particularly valuable in concurrent scenarios, where multiple consumers need to efficiently process real-time data. While we don't cover concurrent consumption in detail in this lesson, it's important to understand this crucial aspect of streams. Consider these real-world scenarios where Redis Streams can be beneficial:

  • Chat Applications: Ideal for real-time message handling.
  • Monitoring Systems: Useful for processing logs and events.
  • User Activity Tracking: Tracks user actions in real time.

Let's dive into the details!

Usage of Commands

To add an event to a stream with PHP, you can use the xadd command.
To read events from a stream, utilize the xread command.

Let's see how these commands work in practice using PHP.

php
1<?php 2 3require 'vendor/autoload.php'; 4 5use Predis\Client; 6 7// Connect to Redis 8$redis = new Client(); 9 10$streamName = 'mystream'; 11 12// Adding events to the stream 13$redis->xadd($streamName, [ 14 'event' => 'login', 15 'user' => 'Alice' 16]); 17 18$redis->xadd($streamName, [ 19 'event' => 'purchase', 20 'user' => 'Bob', 21 'amount' => '100' 22]); 23 24$redis->xadd($streamName, [ 25 'event' => 'add_to_cart', 26 'user' => 'Alice', 27 'product' => 'laptop' 28]); 29 30// Reading events from the stream 31$messages = $redis->xread(20, 0, [$streamName, '0-0']); 32 33if ($messages) { 34 echo "Stream messages:\n"; 35 print_r($messages); 36 37 // Access the first message and print it, if available 38 if (count($messages[$streamName]) > 0) { 39 $firstMessage = $messages[$streamName][0][1]; 40 echo "First message:\n"; 41 print_r($firstMessage); 42 /* 43 Output: 44 Array 45 ( 46 [0] => event 47 [1] => login 48 [2] => user 49 [3] => Alice 50 ) 51 */ 52 } 53} else { 54 echo "No messages found in the stream.\n"; 55} 56 57?>

This PHP code snippet demonstrates how to add events to a Redis stream called mystream using xadd. Each event contains key-value pairs representing different actions by users. The code reads messages from mystream and prints them.

Here is a step by step breakdown:

  1. Autoloading and Namespace Usage: The script begins by including the Composer autoloader to load the Predis library. The use statement imports the Client class from the Predis namespace, allowing the creation of a Redis client instance.

  2. Connecting to Redis: A new instance of the Client class is created, which establishes a connection to the Redis server. By default, it connects to localhost on port 6379, but connection parameters can be customized if needed.

  3. Defining the Stream Name: The variable $streamName is set to 'mystream', which will be the name of the Redis stream used in the operations.

  4. Adding Events to the Stream: The xadd command is used to add events to the stream. Each event is represented as a key-value pair array. In this example, three events are added: a login event by Alice, a purchase event by Bob, and an add-to-cart event by Alice. Each event is stored with a unique ID generated by Redis.

  5. Reading Events from the Stream: The xread command is used to read events from the stream. It specifies the count of messages to read (0 for get all messages), a block time (0 for no blocking), and an array with the stream name and the starting ID ('0-0' to read from the beginning).

  6. Processing and Displaying Messages: The code checks if any messages were retrieved from the stream. If messages are found, it prints them. It also accesses and prints the first message from the stream, demonstrating how to work with individual messages. If no messages are found, it outputs a corresponding message.

Output Format

The output of the first message from the Redis stream is displayed as an associative array, where each key-value pair corresponds to the data added to the stream. In the example provided, the first message output is:

1Array 2( 3 [0] => event 4 [1] => login 5 [2] => user 6 [3] => Alice 7)

This format differs from the original input, which was an associative array with keys and values, such as ['event' => 'login', 'user' => 'Alice']. In the output, the keys and values are presented as sequential elements in a flat array, with even indices representing keys and odd indices representing their corresponding values.

Conclusion

Understanding Redis Streams is crucial for applications that need to process a large volume of real-time data efficiently. Whether you are building a chat application, a monitoring system, or handling user activities and logs, Redis Streams can manage it all.

Through this lesson, you have seen how to handle streams using Redis with PHP. Are you excited to see how Redis Streams can elevate your application? Let's move on to the practice section to get some hands-on experience!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.