ioredis

ioredis

Node.js的全功能Redis客户端

ioredis是一个功能全面的Node.js Redis客户端。它支持Redis集群、哨兵、流处理、管道操作和Lua脚本等特性。ioredis提供直观的API,支持回调和Promise,具备命令参数转换、键前缀等功能。此外,它还支持二进制数据处理、TLS加密和离线队列。ioredis使用TypeScript开发,提供类型声明,兼容Redis 2.6.12及更高版本。

ioredisRedisNode.js数据库高性能Github开源项目

ioredis

Build Status Coverage Status Commitizen friendly semantic-release

Discord Twitch YouTube Twitter

A robust, performance-focused and full-featured Redis client for Node.js.

Supports Redis >= 2.6.12. Completely compatible with Redis 7.x.

Features

ioredis is a robust, full-featured Redis client that is used in the world's biggest online commerce company Alibaba and many other awesome companies.

  1. Full-featured. It supports Cluster, Sentinel, Streams, Pipelining, and of course Lua scripting, Redis Functions, Pub/Sub (with the support of binary messages).
  2. High performance 🚀.
  3. Delightful API 😄. It works with Node callbacks and Native promises.
  4. Transformation of command arguments and replies.
  5. Transparent key prefixing.
  6. Abstraction for Lua scripting, allowing you to define custom commands.
  7. Supports binary data.
  8. Supports TLS 🔒.
  9. Supports offline queue and ready checking.
  10. Supports ES6 types, such as Map and Set.
  11. Supports GEO commands 📍.
  12. Supports Redis ACL.
  13. Sophisticated error handling strategy.
  14. Supports NAT mapping.
  15. Supports autopipelining.

100% written in TypeScript and official declarations are provided:

<img width="837" src="resources/ts-screenshot.png" alt="TypeScript Screenshot" />

Versions

VersionBranchNode.js VersionRedis Version
5.x.x (latest)main>= 122.6.12 ~ latest
4.x.xv4>= 62.6.12 ~ 7

Refer to CHANGELOG.md for features and bug fixes introduced in v5.

🚀 Upgrading from v4 to v5

Links

<hr>

Quick Start

Install

npm install ioredis

In a TypeScript project, you may want to add TypeScript declarations for Node.js:

npm install --save-dev @types/node

Basic Usage

// Import ioredis. // You can also use `import { Redis } from "ioredis"` // if your project is a TypeScript project, // Note that `import Redis from "ioredis"` is still supported, // but will be deprecated in the next major version. const Redis = require("ioredis"); // Create a Redis instance. // By default, it will connect to localhost:6379. // We are going to cover how to specify connection options soon. const redis = new Redis(); redis.set("mykey", "value"); // Returns a promise which resolves to "OK" when the command succeeds. // ioredis supports the node.js callback style redis.get("mykey", (err, result) => { if (err) { console.error(err); } else { console.log(result); // Prints "value" } }); // Or ioredis returns a promise if the last argument isn't a function redis.get("mykey").then((result) => { console.log(result); // Prints "value" }); redis.zadd("sortedSet", 1, "one", 2, "dos", 4, "quatro", 3, "three"); redis.zrange("sortedSet", 0, 2, "WITHSCORES").then((elements) => { // ["one", "1", "dos", "2", "three", "3"] as if the command was `redis> ZRANGE sortedSet 0 2 WITHSCORES` console.log(elements); }); // All arguments are passed directly to the redis server, // so technically ioredis supports all Redis commands. // The format is: redis[SOME_REDIS_COMMAND_IN_LOWERCASE](ARGUMENTS_ARE_JOINED_INTO_COMMAND_STRING) // so the following statement is equivalent to the CLI: `redis> SET mykey hello EX 10` redis.set("mykey", "hello", "EX", 10);

See the examples/ folder for more examples. For example:

All Redis commands are supported. See the documentation for details.

Connect to Redis

When a new Redis instance is created, a connection to Redis will be created at the same time. You can specify which Redis to connect to by:

new Redis(); // Connect to 127.0.0.1:6379 new Redis(6380); // 127.0.0.1:6380 new Redis(6379, "192.168.1.1"); // 192.168.1.1:6379 new Redis("/tmp/redis.sock"); new Redis({ port: 6379, // Redis port host: "127.0.0.1", // Redis host username: "default", // needs Redis >= 6 password: "my-top-secret", db: 0, // Defaults to 0 });

You can also specify connection options as a redis:// URL or rediss:// URL when using TLS encryption:

// Connect to 127.0.0.1:6380, db 4, using password "authpassword": new Redis("redis://:authpassword@127.0.0.1:6380/4"); // Username can also be passed via URI. new Redis("redis://username:authpassword@127.0.0.1:6380/4");

See API Documentation for all available options.

Pub/Sub

Redis provides several commands for developers to implement the Publish–subscribe pattern. There are two roles in this pattern: publisher and subscriber. Publishers are not programmed to send their messages to specific subscribers. Rather, published messages are characterized into channels, without knowledge of what (if any) subscribers there may be.

By leveraging Node.js's built-in events module, ioredis makes pub/sub very straightforward to use. Below is a simple example that consists of two files, one is publisher.js that publishes messages to a channel, the other is subscriber.js that listens for messages on specific channels.

// publisher.js const Redis = require("ioredis"); const redis = new Redis(); setInterval(() => { const message = { foo: Math.random() }; // Publish to my-channel-1 or my-channel-2 randomly. const channel = `my-channel-${1 + Math.round(Math.random())}`; // Message can be either a string or a buffer redis.publish(channel, JSON.stringify(message)); console.log("Published %s to %s", message, channel); }, 1000);
// subscriber.js const Redis = require("ioredis"); const redis = new Redis(); redis.subscribe("my-channel-1", "my-channel-2", (err, count) => { if (err) { // Just like other commands, subscribe() can fail for some reasons, // ex network issues. console.error("Failed to subscribe: %s", err.message); } else { // `count` represents the number of channels this client are currently subscribed to. console.log( `Subscribed successfully! This client is currently subscribed to ${count} channels.` ); } }); redis.on("message", (channel, message) => { console.log(`Received ${message} from ${channel}`); }); // There's also an event called 'messageBuffer', which is the same as 'message' except // it returns buffers instead of strings. // It's useful when the messages are binary data. redis.on("messageBuffer", (channel, message) => { // Both `channel` and `message` are buffers. console.log(channel, message); });

It's worth noticing that a connection (aka a Redis instance) can't play both roles at the same time. More specifically, when a client issues subscribe() or psubscribe(), it enters the "subscriber" mode. From that point, only commands that modify the subscription set are valid. Namely, they are: subscribe, psubscribe, unsubscribe, punsubscribe, ping, and quit. When the subscription set is empty (via unsubscribe/punsubscribe), the connection is put back into the regular mode.

If you want to do pub/sub in the same file/process, you should create a separate connection:

const Redis = require("ioredis"); const sub = new Redis(); const pub = new Redis(); sub.subscribe(/* ... */); // From now, `sub` enters the subscriber mode. sub.on("message" /* ... */); setInterval(() => { // `pub` can be used to publish messages, or send other regular commands (e.g. `hgetall`) // because it's not in the subscriber mode. pub.publish(/* ... */); }, 1000);

PSUBSCRIBE is also supported in a similar way when you want to subscribe all channels whose name matches a pattern:

redis.psubscribe("pat?ern", (err, count) => {}); // Event names are "pmessage"/"pmessageBuffer" instead of "message/messageBuffer". redis.on("pmessage", (pattern, channel, message) => {}); redis.on("pmessageBuffer", (pattern, channel, message) => {});

Streams

Redis v5 introduces a new data type called streams. It doubles as a communication channel for building streaming architectures and as a log-like data structure for persisting data. With ioredis, the usage can be pretty straightforward. Say we have a producer publishes messages to a stream with redis.xadd("mystream", "*", "randomValue", Math.random()) (You may find the official documentation of Streams as a starter to understand the parameters used), to consume the messages, we'll have a consumer with the following code:

const Redis = require("ioredis"); const redis = new Redis(); const processMessage = (message) => { console.log("Id: %s. Data: %O", message[0], message[1]); }; async function listenForMessage(lastId = "$") { // `results` is an array, each element of which corresponds to a key. // Because we only listen to one key (mystream) here, `results` only contains // a single element. See more: https://redis.io/commands/xread#return-value const results = await redis.xread("block", 0, "STREAMS", "mystream", lastId); const [key, messages] = results[0]; // `key` equals to "mystream" messages.forEach(processMessage); // Pass the last id of the results to the next round. await listenForMessage(messages[messages.length - 1][0]); } listenForMessage();

Expiration

Redis can set a timeout to expire your key, after the timeout has expired the key will be automatically deleted. (You can find the official Expire documentation to understand better the different parameters you can use), to set your key to expire in 60 seconds, we will have the following code:

redis.set("key", "data", "EX", 60); // Equivalent to redis command "SET key data EX 60", because on ioredis set method, // all arguments are passed directly to the redis server.

Handle Binary Data

Binary data support is out of the box. Pass buffers to send binary data:

redis.set("foo", Buffer.from([0x62, 0x75, 0x66]));

Every command that returns a bulk string has a variant command with a Buffer suffix. The variant command returns a buffer instead of a UTF-8 string:

const result = await redis.getBuffer("foo"); // result is `<Buffer 62 75 66>`

It's worth noticing that you don't need the Buffer suffix variant in order to send binary data. That means in most case you should just use redis.set() instead of redis.setBuffer() unless you want to get the old value with the GET parameter:

const result = await redis.setBuffer("foo", "new value", "GET"); // result is `<Buffer 62 75 66>` as `GET` indicates returning the old value.

Pipelining

If you want to send a batch of commands (e.g. > 5), you can use pipelining to queue the commands in memory and then send them to Redis all at once. This way the performance improves by 50%~300% (See benchmark section).

redis.pipeline() creates a Pipeline instance. You can call any Redis commands on it just like the Redis instance. The commands are queued in memory and flushed to Redis by calling the exec method:

const pipeline = redis.pipeline(); pipeline.set("foo", "bar"); pipeline.del("cc"); pipeline.exec((err, results) => { // `err` is always null, and `results` is an array of responses // corresponding to the sequence of queued commands. // Each response follows the format `[err, result]`. }); // You can even chain the commands: redis .pipeline() .set("foo", "bar") .del("cc") .exec((err, results) => {}); // `exec` also returns a Promise: const promise = redis.pipeline().set("foo", "bar").get("foo").exec(); promise.then((result) => { // result === [[null, 'OK'], [null, 'bar']] });

Each chained command can also have a callback, which will be invoked when the command gets a reply:

redis .pipeline() .set("foo", "bar") .get("foo", (err, result) => { // result === 'bar' }) .exec((err, result) => { // result[1][1] === 'bar' });

In addition to adding commands to the pipeline queue individually, you can also pass an array of commands and arguments to the constructor:

redis .pipeline([ ["set", "foo", "bar"], ["get", "foo"], ]) .exec(() => { /* ... */ });

#length property shows how many commands in the pipeline:

const length = redis.pipeline().set("foo", "bar").get("foo").length; // length === 2

Transaction

Most of the time, the transaction commands multi & exec are used together with pipeline. Therefore, when multi is called, a Pipeline instance is created automatically by default, so you can use multi just like pipeline:

redis .multi() .set("foo", "bar") .get("foo")

编辑推荐精选

TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

热门AI工具生产力协作转型TraeAI IDE
蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI助手AI工具AI写作工具AI辅助写作蛙蛙写作学术助手办公助手营销助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

聊天机器人AI助手热门AI工具AI对话
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

热门AI工具AI办公办公工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

模型训练热门AI工具内容创作智能问答AI开发讯飞星火大模型多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

AI助手热门AI工具AI创作AI辅助写作讯飞绘文内容运营个性化文章多平台分发
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多