1
0
mirror of https://github.com/redis/node-redis.git synced 2025-08-07 13:22:56 +03:00

Adds example of using a trim strategy with XADD. (#2105)

* Adds example of using a trim strategy with XADD.

* Update stream-producer.js

Co-authored-by: Leibale Eidelman <leibale1998@gmail.com>
This commit is contained in:
Simon Prickett
2022-04-26 14:04:44 +01:00
committed by GitHub
parent b586ccb9d7
commit 225524fabf

View File

@@ -1,5 +1,4 @@
// A sample stream producer using XADD. // A sample stream producer using XADD.
import { createClient } from 'redis'; import { createClient } from 'redis';
async function streamProducer() { async function streamProducer() {
@@ -7,19 +6,46 @@ async function streamProducer() {
await client.connect(); await client.connect();
let num = 0; for (let i = 0; i < 10000; i++) {
await client.xAdd(
'mystream',
'*', // * = Let Redis generate a timestamp ID for this new entry.
// Payload to add to the stream:
{
i: i.toString()
// Other name/value pairs can go here as required...
}
);
while (num < 1000) { // Also add to a stream whose length we will cap at approximately
// * = Let Redis generate a timestamp ID for this new entry. // 1000 entries using the MAXLEN trimming strategy:
let id = await client.xAdd('mystream', '*', { // https://redis.io/commands/xadd/
num: `${num}`
// Other name/value pairs can go here as required...
});
console.log(`Added ${id} to the stream.`); await client.xAdd(
num += 1; 'mytrimmedstream',
id, // Re-use the ID from the previous stream.
// Payload to add to the stream:
{
i: i.toString()
// Other name/value pairs can go here as required...
},
// Specify a trimming strategy...
{
TRIM: {
strategy: 'MAXLEN', // Trim by length.
strategyModifier: '~', // Approximate trimming.
threshold: 1000 // Retain around 1000 entries.
}
}
);
} }
// Take a look at how many entries are in the streams...
// Should be 10000:
console.log(`Length of mystream: ${await client.xLen('mystream')}.`);
// Should be approximately 1000:
console.log(`Length of mytrimmedstream: ${await client.xLen('mytrimmedstream')}.`);
await client.quit(); await client.quit();
} }