# @fastify/redis 中文文档

规范地址：https://npmcn.com/package/%40fastify/redis/

版本：9\.0\.1
npm 元数据更新时间：2026-10-18T12:30:38.609Z
中文译文更新时间：2026-11-14T11:19:16.052Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40fastify/redis
原文对照：https://npmcn.com/package/%40fastify/redis/?lang=original
项目主页：https://github.com/fastify/fastify-redis#readme
源码仓库：https://github.com/fastify/fastify-redis

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：33.8 kB，13 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2022-04-27T14:08:09.687Z
- 最新版本发布：2026-10-09T10:43:54.141Z
- 近 30 天下载量：517860（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：16（近 12 个月 4 个）

## 中文简介

插件, 共享整个快取的 redis 连接 .

## 安装

```sh
npm install @fastify/redis
```

也可以使用：`pnpm add @fastify/redis`、`yarn add @fastify/redis`、`bun add @fastify/redis`

## README

# @ fastify/ redis (中文(简体) )

[![CI](https://github.com/fastify/fastify-redis/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-redis/actions/workflows/ci.yml) [![NPM version](https://img.shields.io/npm/v/@fastify/redis.svg?style=flat)](https://www.npmjs.com/package/@fastify/redis) [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)

Fastify Redis 连接插件; 通过此程序, 您可以在服务器的每个部分共享相同的 Redis 连接 .

## 安装

```
npm i @fastify/redis
```

### 兼容性

| 插件版本 | 快速化版本 |
| --- | --- |
| `>=7.x` | `^5.x` |
| `^6.x` | `^4.x` |
| `>=4.x <6.x` | `^3.x` |
| `^3.x` | `^2.x` |
| `>=1.x <3.x` | `^1.x` |

请注意,如果一个快取版本没有支持,那么该插件的相应版本也一样 上表列出. 见 [快速化 LTS 政策](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) 更多细节.

## 使用量

添加到您的项目中 `register` 你们就完了!

### 创建新的 Redis 客户端

在车盖下 [雄风](https://github.com/redis/ioredis) 用作客户端,该 `options` 你传递给 `register` 将传递给雷迪斯客户端.

```js
const fastify = require('fastify')()

// create by specifying host
fastify.register(require('@fastify/redis'), { host: '127.0.0.1' })

// OR by specifying Redis URL
fastify.register(require('@fastify/redis'), { url: 'redis://127.0.0.1', /* other redis options */ })

// OR with more options
fastify.register(require('@fastify/redis'), {
  host: '127.0.0.1',
  password: '***',
  port: 6379, // Redis port
  family: 4   // 4 (IPv4) or 6 (IPv6)
})
```

### 访问 Redis 客户端

一旦您注册了您的插件, 您可以通过 `fastify.redis`。 。 。 .

结格后客户端自动关闭.

```js
'use strict'

const Fastify = require('fastify')
const fastifyRedis = require('@fastify/redis')

const fastify = Fastify({ logger: true })

fastify.register(fastifyRedis, {
  host: '127.0.0.1',
  password: 'your strong password here',
  port: 6379, // Redis port
  family: 4   // 4 (IPv4) or 6 (IPv6)
})

fastify.get('/foo', (req, reply) => {
  const { redis } = fastify
  redis.get(req.query.key, (err, val) => {
    reply.send(err || val)
  })
})

fastify.post('/foo', (req, reply) => {
  const { redis } = fastify
  redis.set(req.body.key, req.body.value, (err) => {
    reply.send(err || { status: 'ok' })
  })
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})
```

### 使用已有的 Redis 客户端

您也可提供已有的 _重写_ 通过传递选项实现客户端实例 对象与 `client` 属性设置为实例 。 在这种情况下, 当快捷实例出现时,客户端不会自动关闭 关闭.

```js
'use strict'

const fastify = require('fastify')()
const Redis = require('ioredis')

const client = new Redis({ host: 'localhost', port: 6379 })

fastify.register(require('@fastify/redis'), { client })
```

您也可提供 _Redis 集群_ 实例给客户端:

```js
'use strict'

const fastify = require('fastify')()
const Redis = require('ioredis')

const client = new Redis.Cluster([{ host: 'localhost', port: 6379 }]);

fastify.register(require('@fastify/redis'), { client })
```

注:默认情况下, _@ fastify/ redis (中文(简体) )_ 将 **没有** 自动关闭客户端 当快捷服务器关闭时连接 .

要自动关闭客户端连接, 请设置客户端 Close to true.

```js
fastify.register(require('@fastify/redis'), { client, closeClient: true })
```

## 注册多个 Redis 客户端

通过使用 `namespace` 选项,您可以注册多个 Redis 客户端实例.

```js
'use strict'

const fastify = require('fastify')()

fastify
  .register(require('@fastify/redis'), {
    host: '127.0.0.1',
    port: 6380,
    namespace: 'hello'
  })
  .register(require('@fastify/redis'), {
    client: redis,
    namespace: 'world'
  })

// Here we will use the `hello` named instance
fastify.get('/hello', (req, reply) => {
  const { redis } = fastify

  redis.hello.get(req.query.key, (err, val) => {
    reply.send(err || val)
  })
})

fastify.post('/hello', (req, reply) => {
  const { redis } = fastify

  redis['hello'].set(req.body.key, req.body.value, (err) => {
    reply.send(err || { status: 'ok' })
  })
})

// Here we will use the `world` named instance
fastify.get('/world', (req, reply) => {
  const { redis } = fastify

  redis['world'].get(req.query.key, (err, val) => {
    reply.send(err || val)
  })
})

fastify.post('/world', (req, reply) => {
  const { redis } = fastify

  redis.world.set(req.body.key, req.body.value, (err) => {
    reply.send(err || { status: 'ok' })
  })
})

fastify.listen({ port: 3000 }, function (err) {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
})

```

## Redis 流( 需要5. 0 以上)

`@fastify/redis` 支持 Redis 流出框中.

```js
'use strict'

const fastify = require('fastify')()

fastify.register(require('@fastify/redis'), {
  host: '127.0.0.1',
  port: 6380
})

fastify.get('/streams', async (request, reply) => {
  // We write an event to the stream 'my awesome fastify stream name', setting 'key' to 'value'
  await fastify.redis.xadd(['my awesome fastify stream name', '*', 'hello', 'fastify is awesome'])

  // We read events from the beginning of the stream called 'my awesome fastify stream name'
  let redisStream = await fastify.redis.xread(['STREAMS', 'my awesome fastify stream name', 0])

  // We parse the results
  let response = []
  let events = redisStream[0][1]

  for (let i = 0; i < events.length; i++) {
    const e = events[i]
    response.push(`#LOG: id is ${e[0].toString()}`)

    // We log each key
    for (const key in e[1]) {
      response.push(e[1][key].toString())
    }
  }

  reply.status(200)
  return { output: response }
  // Will return something like this :
  // { "output": ["#LOG: id is 1559985742035-0", "hello", "fastify is awesome"] }
})

fastify.listen({ port: 3000 }, function (err) {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
})
```

> iQQ: 您可以找到更多关于 Redis 流和相关命令的信息 [这里](https://redis.io/docs/latest/develop/use-cases/streaming/) 财务报告和审定财务报表 [这里](https://redis.io/docs/latest/commands/?group=stream)。 。 。 .

## Redis 连接出错

大部分错误都因为 `ioredis` 静态错误处理, 但在插件注册期间, 它会检查与 redis 实例的连接是否正确稳定 . 在这种情况下,你可以接受 `ERR_AVVIO_PLUGIN_TIMEOUT` 如果连接无法在预期的时间框架内建立,或者一个无效连接的专用错误,则错误.

## 承认

这个项目由下列各方慷慨赞助:

-   [临近格式](https://nearform.com/)

过去提案国:

-   莱兹

## 许可证

许可证根据 [麻省理工学院](https://npmcn.com/package/%40fastify/redis/LICENSE)。 。 。 .

## 常见问题

### @fastify/redis 是什么？

插件, 共享整个快取的 redis 连接 \.

### 如何安装 @fastify/redis？

在项目目录运行 npm install @fastify/redis，或使用 pnpm add / yarn add / bun add。

### @fastify/redis 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @fastify/redis 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @fastify/redis 可以商用吗？

@fastify/redis 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @fastify/redis 的下载量有多少？

根据 npm 官方下载统计，@fastify/redis 在 2026/10/15 – 2026/11/13 这 30 天内被下载 517,860 次，日均约 17,262 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @fastify/redis 还在维护吗？

最新版本 9\.0\.1 发布于 2026/10/09（1 个月前）；至今共发布 16 个版本，其中过去 12 个月发布了 4 个；首次发布于 2022/04/27。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

