The XADD
command in Redis is used to append new entries to a stream. This is especially useful in tracking activities or events where chronological order and data persistence are needed, such as user activity logs, IoT sensor data, real-time analytics, etc.
First, you need to make sure you have the Predis client installed for PHP. If not, you can use composer:
composer require predis/predis
Here's an example of how to use XADD
with PHP:
require 'vendor/autoload.php'; $client = new Predis\Client(); // Add an event to the stream 'mystream' $client->xadd('mystream', '*', ['temperature' => 22.5, 'humidity' => 60]);
In this example, we're adding an entry to the 'mystream' stream. The '*' argument tells Redis to assign an automatic ID to this entry. The array that follows includes the fields and their respective values in the stream entry.
XADD
, itโs good practice to allow Redis to auto-generate IDs by using '*'. These IDs are guaranteed to be unique and ordered by the exact moment they were created.Q: Can I use my own ID when adding entries to a stream?
A: Yes, you can specify your own ID as long as it follows the format of a millisecond timestamp plus a sequence number (like 1518951480106-0). However, it's generally simpler and safer to let Redis auto-generate the ID using '*'.
Q: What happens if I try to add an entry to a non-existing stream?
A: If a specified stream does not exist, Redis will automatically create it when you try to add an entry. This feature allows streams to be used without explicit prior creation.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.