Skip to content

Commit 225524f

Browse files
Simon Prickettleibale
andauthored
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 <[email protected]>
1 parent b586ccb commit 225524f

File tree

1 file changed

+39
-13
lines changed

1 file changed

+39
-13
lines changed

examples/stream-producer.js

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,51 @@
11
// A sample stream producer using XADD.
2-
32
import { createClient } from 'redis';
43

54
async function streamProducer() {
65
const client = createClient();
76

87
await client.connect();
9-
10-
let num = 0;
11-
12-
while (num < 1000) {
13-
// * = Let Redis generate a timestamp ID for this new entry.
14-
let id = await client.xAdd('mystream', '*', {
15-
num: `${num}`
16-
// Other name/value pairs can go here as required...
17-
});
18-
19-
console.log(`Added ${id} to the stream.`);
20-
num += 1;
8+
9+
for (let i = 0; i < 10000; i++) {
10+
await client.xAdd(
11+
'mystream',
12+
'*', // * = Let Redis generate a timestamp ID for this new entry.
13+
// Payload to add to the stream:
14+
{
15+
i: i.toString()
16+
// Other name/value pairs can go here as required...
17+
}
18+
);
19+
20+
// Also add to a stream whose length we will cap at approximately
21+
// 1000 entries using the MAXLEN trimming strategy:
22+
// https://redis.io/commands/xadd/
23+
24+
await client.xAdd(
25+
'mytrimmedstream',
26+
id, // Re-use the ID from the previous stream.
27+
// Payload to add to the stream:
28+
{
29+
i: i.toString()
30+
// Other name/value pairs can go here as required...
31+
},
32+
// Specify a trimming strategy...
33+
{
34+
TRIM: {
35+
strategy: 'MAXLEN', // Trim by length.
36+
strategyModifier: '~', // Approximate trimming.
37+
threshold: 1000 // Retain around 1000 entries.
38+
}
39+
}
40+
);
2141
}
2242

43+
// Take a look at how many entries are in the streams...
44+
// Should be 10000:
45+
console.log(`Length of mystream: ${await client.xLen('mystream')}.`);
46+
// Should be approximately 1000:
47+
console.log(`Length of mytrimmedstream: ${await client.xLen('mytrimmedstream')}.`);
48+
2349
await client.quit();
2450
}
2551

0 commit comments

Comments
 (0)