Redis 中文文档 Redis 中文文档
指南
redis.io (opens new window)
指南
redis.io (opens new window)
  • 关于
    • Redis 开源治理
    • Redis 发布周期
    • Redis 赞助商
  • 入门
  • 数据类型
  • Redis Stack
  • 命令
  • 手册

Node-Redis


node-redis is a modern, high performance Redis client for Node.js.

Packages


Name Description
:--- :---
redis
@redis/client
@redis/bloom Redis Bloom commands
@redis/graph Redis Graph commands
@redis/json Redis JSON commands
@redis/search RediSearch commands
@redis/time-series Redis Time-Series commands

⚠️In version 4.1.0 we moved our subpackages from @node-redis to @redis. If you're just using npm install redis, you don't need to do anything—it'll upgrade automatically. If you're using the subpackages directly, you'll need to point to the new scope (e.g. @redis/client instead of @node-redis/client ).


Installation


Start a redis via docker:

  1. ``` shell
  2. docker run -p 6379:6379 -it redis/redis-stack-server:latest
  3. ```

To install node-redis, simply:

  1. ``` shell
  2. npm install redis
  3. ```

⚠️The new interface is clean and cool, but if you have an existing codebase, you'll want to read the migration guide.


Looking for a high-level library to handle object mapping? See redis-om-node !

Usage


Basic Example


  1. ``` ts
  2. import { createClient } from 'redis';

  3. const client = createClient();

  4. client.on('error', err => console.log('Redis Client Error', err));

  5. await client.connect();

  6. await client.set('key', 'value');
  7. const value = await client.get('key');
  8. await client.disconnect();
  9. ```

The above code connects to localhost on port 6379. To connect to a different host or port, use a connection string in the format redis[s]://[[username][:password]@][host][:port][/db-number] :

  1. ``` ts
  2. createClient({
  3.   url: 'redis://alice:foobared@awesome.redis.server:6380'
  4. });
  5. ```

You can also use discrete parameters, UNIX sockets, and even TLS to connect. Details can be found in the client configuration guide.

To check if the the client is connected and ready to send commands, use client.isReady which returns a boolean. client.isOpen is also available.  This returns true when the client's underlying socket is open, and false when it isn't (for example when the client is still connecting or reconnecting after a network error).

Redis Commands


There is built-in support for all of the out-of-the-box Redis commands. They are exposed using the raw Redis command names (HSET, HGETALL, etc.) and a friendlier camel-cased version (hSet, hGetAll, etc.):

  1. ``` ts
  2. // raw Redis commands
  3. await client.HSET('key', 'field', 'value');
  4. await client.HGETALL('key');

  5. // friendly JavaScript commands
  6. await client.hSet('key', 'field', 'value');
  7. await client.hGetAll('key');
  8. ```

Modifiers to commands are specified using a JavaScript object:

  1. ``` ts
  2. await client.set('key', 'value', {
  3.   EX: 10,
  4.   NX: true
  5. });
  6. ```

Replies will be transformed into useful data structures:

  1. ``` ts
  2. await client.hGetAll('key'); // { field1: 'value1', field2: 'value2' }
  3. await client.hVals('key'); // ['value1', 'value2']
  4. ```

Buffer s are supported as well:

  1. ``` ts
  2. await client.hSet('key', 'field', Buffer.from('value')); // 'OK'
  3. await client.hGetAll(
  4.   commandOptions({ returnBuffers: true }),
  5.   'key'
  6. ); // { field: }
  7. ```

Unsupported Redis Commands


If you want to run commands and/or use arguments that Node Redis doesn't know about (yet!) use .sendCommand() :

  1. ``` ts
  2. await client.sendCommand(['SET', 'key', 'value', 'NX']); // 'OK'

  3. await client.sendCommand(['HGETALL', 'key']); // ['key1', 'field1', 'key2', 'field2']
  4. ```

Transactions (Multi/Exec)


Start a transaction by calling .multi(), then chaining your commands. When you're done, call .exec() and you'll get an array back with your results:

  1. ``` ts
  2. await client.set('another-key', 'another-value');

  3. const [setKeyReply, otherKeyValue] = await client
  4.   .multi()
  5.   .set('key', 'value')
  6.   .get('another-key')
  7.   .exec(); // ['OK', 'another-value']
  8. ```

You can also watch keys by calling .watch(). Your transaction will abort if any of the watched keys change.

To dig deeper into transactions, check out the Isolated Execution Guide.

Blocking Commands


Any command can be run on a new connection by specifying the isolated option. The newly created connection is closed when the command's Promise is fulfilled.

This pattern works especially well for blocking commands—such as BLPOP and BLMOVE :

  1. ``` ts
  2. import { commandOptions } from 'redis';

  3. const blPopPromise = client.blPop(
  4.   commandOptions({ isolated: true }),
  5.   'key',
  6.   0
  7. );

  8. await client.lPush('key', ['1', '2']);

  9. await blPopPromise; // '2'
  10. ```

To learn more about isolated execution, check out the guide.

Pub/Sub


See the Pub/Sub overview.

Scan Iterator


SCAN results can be looped over using async iterators :

  1. ``` ts
  2. for await (const key of client.scanIterator()) {
  3.   // use the key!
  4.   await client.get(key);
  5. }
  6. ```

This works with HSCAN, SSCAN, and ZSCAN too:

  1. ``` ts
  2. for await (const { field, value } of client.hScanIterator('hash')) {}
  3. for await (const member of client.sScanIterator('set')) {}
  4. for await (const { score, value } of client.zScanIterator('sorted-set')) {}
  5. ```

You can override the default options by providing a configuration object:

  1. ``` ts
  2. client.scanIterator({
  3.   TYPE: 'string', // `SCAN` only
  4.   MATCH: 'patter*',
  5.   COUNT: 100
  6. });
  7. ```

Programmability


Redis provides a programming interface allowing code execution on the redis server.

Functions


The following example retrieves a key in redis, returning the value of the key, incremented by an integer. For example, if your key foohas the value 17and we run add('foo', 25), it returns the answer to Life, the Universe and Everything.

  1. ``` lua
  2. #!lua name=library

  3. redis.register_function {
  4.   function_name = 'add',
  5.   callback = function(keys, args) return redis.call('GET', keys[1]) + args[1] end,
  6.   flags = { 'no-writes' }
  7. }
  8. ```

Here is the same example, but in a format that can be pasted into the redis-cli.

  1. ``` sh
  2. FUNCTION LOAD "#!lua name=library\nredis.register_function{function_name=\"add\", callback=function(keys, args) return redis.call('GET', keys[1])+args[1] end, flags={\"no-writes\"}}"

  3. ```

Load the prior redis function on the redis serverbefore running the example below.

  1. ``` ts
  2. import { createClient } from 'redis';

  3. const client = createClient({
  4.   functions: {
  5.     library: {
  6.       add: {
  7.         NUMBER_OF_KEYS: 1,
  8.         transformArguments(key: string, toAdd: number): Array<string> {
  9.           return [key, toAdd.toString()];
  10.         },
  11.         transformReply(reply: number): number {
  12.           return reply;
  13.         }
  14.       }
  15.     }
  16.   }
  17. });

  18. await client.connect();

  19. await client.set('key', '1');
  20. await client.library.add('key', 2); // 3
  21. ```

Lua Scripts


The following is an end-to-end example of the prior concept.

  1. ``` ts
  2. import { createClient, defineScript } from 'redis';

  3. const client = createClient({
  4.   scripts: {
  5.     add: defineScript({
  6.       NUMBER_OF_KEYS: 1,
  7.       SCRIPT:
  8.         'return redis.call("GET", KEYS[1]) + ARGV[1];',
  9.       transformArguments(key: string, toAdd: number): Array<string> {
  10.         return [key, toAdd.toString()];
  11.       },
  12.       transformReply(reply: number): number {
  13.         return reply;
  14.       }
  15.     })
  16.   }
  17. });

  18. await client.connect();

  19. await client.set('key', '1');
  20. await client.add('key', 2); // 3
  21. ```

Disconnecting


There are two functions that disconnect a client from the Redis server. In most scenarios you should use .quit() to ensure that pending commands are sent to Redis before closing a connection.

.QUIT()/.quit()


Gracefully close a client's connection to Redis, by sending the QUIT command to the server. Before quitting, the client executes any remaining commands in its queue, and will receive replies from Redis for each of them.

  1. ``` ts
  2. const [ping, get, quit] = await Promise.all([
  3.   client.ping(),
  4.   client.get('key'),
  5.   client.quit()
  6. ]); // ['PONG', null, 'OK']

  7. try {
  8.   await client.get('key');
  9. } catch (err) {
  10.   // ClosedClient Error
  11. }
  12. ```

.disconnect()


Forcibly close a client's connection to Redis immediately. Calling disconnect will not send further pending commands to the Redis server, or wait for or parse outstanding responses.

  1. ``` ts
  2. await client.disconnect();
  3. ```

Auto-Pipelining


Node Redis will automatically pipeline requests that are made during the same "tick".

  1. ``` ts
  2. client.set('Tm9kZSBSZWRpcw==', 'users:1');
  3. client.sAdd('users:1:tokens', 'Tm9kZSBSZWRpcw==');
  4. ```

Of course, if you don't do something with your Promises you're certain to get unhandled Promise exceptions. To take advantage of auto-pipelining and handle your Promises, use Promise.all().

  1. ``` ts
  2. await Promise.all([
  3.   client.set('Tm9kZSBSZWRpcw==', 'users:1'),
  4.   client.sAdd('users:1:tokens', 'Tm9kZSBSZWRpcw==')
  5. ]);
  6. ```

Clustering


Check out the Clustering Guide when using Node Redis to connect to a Redis Cluster.

Events


The Node Redis client class is an Nodejs EventEmitter and it emits an event each time the network status changes:

Name When Listener arguments
:--- :--- :---
connect Initiating a connection to the server No arguments
ready Client is ready to use No arguments
end Connection has been closed (via .quit() or .disconnect()) No arguments
error An error has occurred—usually a network issue such as "Socket closed unexpectedly" (error: Error)
reconnecting Client is trying to reconnect to the server No arguments
sharded-channel-moved See here See here

⚠️You MUSTlisten to error events. If a client doesn't have at least one error listener registered and an error occurs, that error will be thrown and the Node.js process will exit. See the EventEmitter docs for more details.


The client will not emit any other events beyond those listed above.


Supported Redis versions


Node Redis is supported with the following versions of Redis:

Version Supported
:--- :---
7.0.z ✔️
6.2.z ✔️
6.0.z ✔️
5.0.z ✔️
< 5.0 ❌

Node Redis should work with older versions of Redis, but it is not fully tested and we cannot offer support.


Contributing


If you'd like to contribute, check out the contributing guide.

Thank you to all the people who already contributed to Node Redis!

License


This repository is licensed under the "MIT" license. See LICENSE.
Last Updated: 2023-09-03 19:17:54