You've already forked node-redis
mirror of
https://github.com/redis/node-redis.git
synced 2025-08-06 02:15:48 +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:
@@ -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,18 +6,45 @@ async function streamProducer() {
|
|||||||
|
|
||||||
await client.connect();
|
await client.connect();
|
||||||
|
|
||||||
let num = 0;
|
for (let i = 0; i < 10000; i++) {
|
||||||
|
await client.xAdd(
|
||||||
while (num < 1000) {
|
'mystream',
|
||||||
// * = Let Redis generate a timestamp ID for this new entry.
|
'*', // * = Let Redis generate a timestamp ID for this new entry.
|
||||||
let id = await client.xAdd('mystream', '*', {
|
// Payload to add to the stream:
|
||||||
num: `${num}`
|
{
|
||||||
|
i: i.toString()
|
||||||
// Other name/value pairs can go here as required...
|
// Other name/value pairs can go here as required...
|
||||||
});
|
|
||||||
|
|
||||||
console.log(`Added ${id} to the stream.`);
|
|
||||||
num += 1;
|
|
||||||
}
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Also add to a stream whose length we will cap at approximately
|
||||||
|
// 1000 entries using the MAXLEN trimming strategy:
|
||||||
|
// https://redis.io/commands/xadd/
|
||||||
|
|
||||||
|
await client.xAdd(
|
||||||
|
'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();
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user