@keyv/redis 3.0.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,93 +9,230 @@
9
9
 
10
10
  Redis storage adapter for [Keyv](https://github.com/jaredwray/keyv).
11
11
 
12
- TTL functionality is handled directly by Redis so no timestamps are stored and expired keys are cleaned up internally.
12
+ # Features
13
+ * Built on top of [redis](https://npmjs.com/package/redis).
14
+ * TTL is handled directly by Redis.
15
+ * Supports Redis Clusters.
16
+ * Url connection string support or pass in your Redis Options
17
+ * Easily add in your own Redis client.
18
+ * Namespace support for key management.
19
+ * Unlink as default delete method for performance.
20
+ * Access to the Redis client for advanced use cases.
21
+ * Keyv and Redis Libraries are exported for advanced use cases.
22
+ * `createKeyv` function for easy creation of Keyv instances.
23
+ * jsDoc comments for easy documentation.
24
+ * CJS / ESM and TypeScript supported out of the box.
25
+
26
+ # Table of Contents
27
+ * [Usage](#usage)
28
+ * [Namespaces](#namespaces)
29
+ * [Performance Considerations](#performance-considerations)
30
+ * [High Memory Usage on Redis Server](#high-memory-usage-on-redis-server)
31
+ * [Using Cacheable with Redis](#using-cacheable-with-redis)
32
+ * [Clustering and TLS Support](#clustering-and-tls-support)
33
+ * [API](#api)
34
+ * [Migrating from v3 to v4](#migrating-from-v3-to-v4)
35
+ * [About Redis Sets and its Support in v4](#about-redis-sets-and-its-support-in-v4)
36
+ * [License](#license)
37
+
38
+ # Usage
39
+
40
+ Here is a standard use case where we implement `Keyv` and `@keyv/redis`:
13
41
 
14
- ## Install
42
+ ```js
43
+ import Keyv from 'keyv';
44
+ import KeyvRedis from '@keyv/redis';
15
45
 
16
- ```shell
17
- npm install --save keyv @keyv/redis
46
+ const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'));
47
+ keyv.on('error', handleConnectionError);
18
48
  ```
19
49
 
20
- ## Usage
50
+ Here you can pass in the Redis options directly:
21
51
 
22
52
  ```js
23
53
  import Keyv from 'keyv';
24
54
  import KeyvRedis from '@keyv/redis';
25
55
 
26
- const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'));
27
- keyv.on('error', handleConnectionError);
28
- ```
56
+ const redisOptions = {
57
+ url: 'redis://localhost:6379', // The Redis server URL (use 'rediss' for TLS)
58
+ password: 'your_password', // Optional password if Redis has authentication enabled
29
59
 
30
- Any valid [`Redis`](https://github.com/luin/ioredis#connect-to-redis) options will be passed directly through.
60
+ socket: {
61
+ host: 'localhost', // Hostname of the Redis server
62
+ port: 6379, // Port number
63
+ reconnectStrategy: (retries) => Math.min(retries * 50, 2000), // Custom reconnect logic
31
64
 
32
- e.g:
65
+ tls: false, // Enable TLS if you need to connect over SSL
66
+ keepAlive: 30000, // Keep-alive timeout (in milliseconds)
67
+ }
68
+ };
33
69
 
34
- ```js
35
- const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379', { disable_resubscribing: true }));
70
+ const keyv = new Keyv(new KeyvRedis(redisOptions));
36
71
  ```
37
72
 
38
- Or you can manually create a storage adapter instance and pass it to Keyv:
73
+ Or you can create a new Redis instance and pass it in with `KeyvOptions`:
39
74
 
40
75
  ```js
41
76
  import Keyv from 'keyv';
42
- import KeyvRedis from '@keyv/redis';
77
+ import KeyvRedis, { createClient } from '@keyv/redis';
43
78
 
44
- const keyvRedis = new KeyvRedis('redis://user:pass@localhost:6379');
79
+ const redis = createClient('redis://user:pass@localhost:6379', { namespace: 'my-namespace'});
80
+ const keyvRedis = new KeyvRedis(redis);
45
81
  const keyv = new Keyv({ store: keyvRedis });
46
82
  ```
47
83
 
48
- Or reuse a previous Redis instance:
84
+ Here is the same example but with the `Keyv` instance created with the `createKeyv` function:
49
85
 
50
86
  ```js
51
- import Keyv from 'keyv';
52
- import Redis from 'ioredis';
53
- import KeyvRedis from '@keyv/redis';
87
+ import { createKeyv } from '@keyv/redis';
54
88
 
55
- const redis = new Redis('redis://user:pass@localhost:6379');
56
- const keyvRedis = new KeyvRedis(redis);
57
- const keyv = new Keyv({ store: keyvRedis });
89
+ const keyv = createKeyv('redis://user:pass@localhost:6379', { namespace: 'my-namespace' });
58
90
  ```
59
91
 
60
- Or reuse a previous Redis cluster:
92
+ You only have to import the `@keyv/redis` library if you are using the `createKeyv` function. 🎉 Otherwise, you can import `Keyv` and `@keyv/redis` independently.
93
+
94
+ # Namspaces
95
+
96
+ You can set a namespace for your keys. This is useful if you want to manage your keys in a more organized way. Here is an example of how to set a namespace:
61
97
 
62
98
  ```js
63
99
  import Keyv from 'keyv';
64
- import Redis from 'ioredis';
65
100
  import KeyvRedis from '@keyv/redis';
66
101
 
67
- const redis = new Redis.Cluster('redis://user:pass@localhost:6379');
68
- const keyvRedis = new KeyvRedis(redis);
69
- const keyv = new Keyv({ store: keyvRedis });
102
+ const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379', { namespace: 'my-namespace' }));
70
103
  ```
71
- ## Options
72
104
 
73
- ### useRedisSets
105
+ This will prefix all keys with `my-namespace:`. You can also set the namespace after the fact:
106
+
107
+ ```js
108
+ keyv.namespace = 'my-namespace';
109
+ ```
110
+
111
+ NOTE: If you plan to do many clears or deletes, it is recommended to read the [Performance Considerations](#performance-considerations) section.
112
+
113
+ # Performance Considerations
114
+
115
+ With namespaces being prefix based it is critical to understand some of the performance considerations we have made:
116
+ * `clear()` - We use the `SCAN` command to iterate over keys. This is a non-blocking command that is more efficient than `KEYS`. In addition we are using `UNLINK` by default instead of `DEL`. Even with that if you are iterating over a large dataset it can still be slow. It is highly recommended to use the `namespace` option to limit the keys that are being cleared and if possible to not use the `clear()` method in high performance environments.
74
117
 
75
- The `useRedisSets` option lets you decide whether to use Redis sets for key management. By default, this option is set to `true`.
118
+ * `delete()` - By default we are now using `UNLINK` instead of `DEL` for deleting keys. This is a non-blocking command that is more efficient than `DEL`. If you are deleting a large number of keys it is recommended to use the `deleteMany()` method instead of `delete()`.
76
119
 
77
- When `useRedisSets` is enabled (`true`):
120
+ * `clearBatchSize` - The `clearBatchSize` option is set to `1000` by default. This is because Redis has a limit of 1000 keys that can be deleted in a single batch.
78
121
 
79
- - A namespace for the Redis sets is created, and all created keys are added to this. This allows for group management of keys.
80
- - When a key is deleted, it's removed not only from the main storage but also from the Redis set.
81
- - When clearing all keys (using the `clear` function), all keys in the Redis set are looked up for deletion. The set itself is also deleted.
122
+ * `useUnlink` - This option is set to `true` by default. This is because `UNLINK` is a non-blocking command that is more efficient than `DEL`. If you are not using `UNLINK` and are doing a lot of deletes it is recommended to set this option to `true`.
82
123
 
83
- **Note**: In high-performance scenarios, enabling `useRedisSets` might lead to memory leaks. If you're running a high-performance application or service, it is recommended to set `useRedisSets` to `false`.
124
+ * `setMany`, `getMany`, `deleteMany` - These methods are more efficient than their singular counterparts. If you are doing multiple operations it is recommended to use these methods.
84
125
 
85
- If you decide to set `useRedisSets` as `false`, keys will be handled individually and Redis sets won't be utilized.
126
+ If you want to see even better performance please see the [Using Cacheable with Redis](#using-cacheable-with-redis) section as it has non-blocking and in-memory primary caching that goes along well with this library and Keyv.
86
127
 
87
- However, please note that setting `useRedisSets` to `false` could lead to performance issues in production when using the `clear` function, as it will need to iterate over all keys to delete them.
128
+ # High Memory Usage on Redis Server
88
129
 
89
- #### Example
130
+ This is because we are using `UNLINK` by default instead of `DEL`. This is a non-blocking command that is more efficient than `DEL` but will slowly remove the memory allocation.
90
131
 
91
- Here's how you can use the `useRedisSets` option:
132
+ If you are deleting or clearing a large number of keys you can disable this by setting the `useUnlink` option to `false`. This will use `DEL` instead of `UNLINK` and should reduce the memory usage.
133
+
134
+ ```js
135
+ const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379', { useUnlink: false }));
136
+ // Or
137
+ keyv.useUnlink = false;
138
+ ```
139
+
140
+ # Using Cacheable with Redis
141
+
142
+ If you are wanting to see even better performance with Redis, you can use [Cacheable](https://npmjs.org/package/cacheable) which is a multi-layered cache library that has in-memory primary caching and non-blocking secondary caching. Here is an example of how to use it with Redis:
143
+
144
+ ```js
145
+ import KeyvRedis from '@keyv/redis';
146
+ import Cacheable from 'cacheable';
147
+
148
+ const secondary = new KeyvRedis('redis://user:pass@localhost:6379');
149
+
150
+ const cache = new Cacheable( { secondary } );
151
+ ```
152
+
153
+ For even higher performance you can set the `nonBlocking` option to `true`:
154
+
155
+ ```js
156
+ const cache = new Cacheable( { secondary, nonBlocking: true } );
157
+ ```
158
+
159
+ This will make it so that the secondary does not block the primary cache and will be very fast. 🚀
160
+
161
+ # Clustering and TLS Support
162
+
163
+ If you are using a Redis Cluster or need to use TLS, you can pass in the `redisOptions` directly. Here is an example of how to do that:
92
164
 
93
165
  ```js
94
166
  import Keyv from 'keyv';
167
+ import KeyvRedis, { createCluster } from '@keyv/redis';
168
+
169
+ const cluster = createCluster({
170
+ rootNodes: [
171
+ {
172
+ url: 'redis://127.0.0.1:7000',
173
+ },
174
+ {
175
+ url: 'redis://127.0.0.1:7001',
176
+ },
177
+ {
178
+ url: 'redis://127.0.0.1:7002',
179
+ },
180
+ ],
181
+ });
182
+
183
+ const keyv = new Keyv({ store: new KeyvRedis(cluster) });
184
+ ```
185
+
186
+ Here is an example of how to use TLS:
187
+
188
+ ```js
189
+ import Keyv from 'keyv';
190
+ import KeyvRedis from '@keyv/redis';
95
191
 
96
- const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379', { useRedisSets: false }));
192
+ const tlsOptions = {
193
+ socket: {
194
+ host: 'localhost',
195
+ port: 6379,
196
+ tls: true, // Enable TLS connection
197
+ rejectUnauthorized: false, // Ignore self-signed certificate errors (for testing)
198
+
199
+ // Alternatively, provide CA, key, and cert for mutual authentication
200
+ ca: fs.readFileSync('/path/to/ca-cert.pem'),
201
+ cert: fs.readFileSync('/path/to/client-cert.pem'), // Optional for client auth
202
+ key: fs.readFileSync('/path/to/client-key.pem'), // Optional for client auth
203
+ }
204
+ };
205
+
206
+ const keyv = new Keyv({ store: new KeyvRedis(tlsOptions) });
97
207
  ```
98
208
 
99
- ## License
209
+ # API
210
+ * **constructor([connection], [options])**
211
+ * **namespace** - The namespace to use for the keys.
212
+ * **client** - The Redis client instance.
213
+ * **keyPrefixSeparator** - The separator to use between the namespace and key.
214
+ * **clearBatchSize** - The number of keys to delete in a single batch.
215
+ * **useUnlink** - Use the `UNLINK` command for deleting keys isntead of `DEL`.
216
+ * **set** - Set a key.
217
+ * **setMany** - Set multiple keys.
218
+ * **get** - Get a key.
219
+ * **getMany** - Get multiple keys.
220
+ * **has** - Check if a key exists.
221
+ * **hasMany** - Check if multiple keys exist.
222
+ * **delete** - Delete a key.
223
+ * **deleteMany** - Delete multiple keys.
224
+ * **clear** - Clear all keys. If the `namespace` is set it will only clear keys with that namespace.
225
+ * **disconnect** - Disconnect from the Redis server.
226
+ * **iterator** - Create a new iterator for the keys.
227
+
228
+ # Migrating from v3 to v4
229
+
230
+ The main change in v4 is the removal of the `ioredis` library in favor of the `@keyv/redis` library. This was done to provide a more consistent experience across all Keyv storage adapters. The `@keyv/redis` library is a wrapper around the `redis` library and provides a more consistent experience across all Keyv storage adapters. The only other change is that we no longer do redis sets as they caused performance issues.
231
+
232
+ # About Redis Sets and its Support in v4
233
+
234
+ We no longer support redis sets. This is due to the fact that it caused significant performance issues and was not a good fit for the library.
235
+
236
+ # License
100
237
 
101
238
  [MIT © Jared Wray](LISCENCE)