node-redis 指南 (JavaScript)

将 Node.js/JavaScript 应用程序连接到 Redis 数据库

node-redis 是适用于 Node.js/JavaScript 的 Redis 客户端。 以下部分介绍了如何安装node-redis并连接您的应用程序 添加到 Redis 数据库。

node-redis需要正在运行的 Redis 或 Redis Stack 服务器。请参阅 Redis 安装说明入门

您还可以使用对象映射客户端界面访问 Redis。有关更多信息,请参阅 RedisOM for Node.js

安装

要安装 node-redis,请运行:

npm install redis

Connect and test

Connect to localhost on port 6379.

import { createClient } from 'redis';

const client = createClient();

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

await client.connect();

Store and retrieve a simple string.

await client.set('key', 'value');
const value = await client.get('key');

Store and retrieve a map.

await client.hSet('user-session:123', {
    name: 'John',
    surname: 'Smith',
    company: 'Redis',
    age: 29
})

let userSession = await client.hGetAll('user-session:123');
console.log(JSON.stringify(userSession, null, 2));
/*
{
  "surname": "Smith",
  "name": "John",
  "company": "Redis",
  "age": "29"
}
 */

To connect to a different host or port, use a connection string in the format redis[s]://[[username][:password]@][host][:port][/db-number]:

createClient({
  url: 'redis://alice:foobared@awesome.redis.server:6380'
});

To check if 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).

More information

The node-redis website has more examples. The Github repository also has useful information, including a guide to the connection configuration options you can use.

See also the other pages in this section for more information and examples: