|
1 | 1 | // A sample stream producer using XADD.
|
2 |
| - |
3 | 2 | import { createClient } from 'redis';
|
4 | 3 |
|
5 | 4 | async function streamProducer() {
|
6 | 5 | const client = createClient();
|
7 | 6 |
|
8 | 7 | 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 | + ); |
21 | 41 | }
|
22 | 42 |
|
| 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 | + |
23 | 49 | await client.quit();
|
24 | 50 | }
|
25 | 51 |
|
|
0 commit comments