# @fastify/circuit-breaker 中文文档

规范地址：https://npmcn.com/package/%40fastify/circuit-breaker/

版本：4\.0\.4
npm 元数据更新时间：2026-10-18T12:30:26.947Z
中文译文更新时间：2026-11-14T11:24:21.851Z
软件包许可：MIT

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

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

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

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

## 中文简介

低通航线断路器

## 安装

```sh
npm install @fastify/circuit-breaker
```

也可以使用：`pnpm add @fastify/circuit-breaker`、`yarn add @fastify/circuit-breaker`、`bun add @fastify/circuit-breaker`

## README

![](https://martinfowler.com/bliki/images/circuitBreaker/state.png)

# @ fastify/ 断路器

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

低额管理费 [断路器](https://martinfowler.com/bliki/CircuitBreaker.html) 为你的路线.

## 安装

```
npm i @fastify/circuit-breaker
```

### 兼容性

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

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

## 使用量

注册插件,并在必要时通过自定义选项.  
此插件将添加一个 `onSend` 钩上并暴露 `circuitBreaker` 函数.  
打电话 `fastify.circuitBreaker()` 当宣布 `preHandler` 选项,您将以此方式将该非常具体的路径置于 _断路_ 检查.

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

fastify.register(require('@fastify/circuit-breaker'))

fastify.register(function (instance, opts, next) {
  instance.route({
    method: 'GET',
    url: '/',
    schema: {
      querystring: {
        error: { type: 'boolean' },
        delay: { type: 'number' }
      }
    },
    preHandler: instance.circuitBreaker(),
    handler: function (req, reply) {
      setTimeout(() => {
        reply.send(
          req.query.error ? new Error('kaboom') : { hello: 'world' }
        )
      }, req.query.delay || 0)
    }
  })
  next()
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log('Server listening at http://localhost:3000')
})
```

### 选项

您可以在插件注册期间通过以下选项, 这样所有路由都会使用这些值 .

```js
fastify.register(require('@fastify/circuit-breaker'), {
  threshold: 3, // default 5
  timeout: 5000, // default 10000
  resetTimeout: 5000, // default 10000
  onCircuitOpen: async (req, reply) => {
    reply.statusCode = 500
    throw new Error('a custom error')
  },
  onTimeout: async (req, reply) => {
    reply.statusCode = 504
    return 'timed out'
  }
})
```

-   `threshold`:打开回路前接受的最大故障次数.
-   `timeout:` 返回前最多可等待的毫秒数 `TimeoutError`。 。 。 .
-   `resetTimeout`: 电路移动前的毫秒数 `open` 改为 `half-open`
-   `onCircuitOpen`: 当电路是 `open` 由于错误。 它可以修改答复并返回 a `string` | `Buffer` | `Stream` 载荷。 如果一个 `Error` 它将被扔到您的错误处理器.
-   `onTimeout`: 当电路是 `open` 由于超时。 它可以修改答复并返回 a `string` | `Buffer` | `Stream` | `Error` 载荷。 如果一个 `Error` 它将被扔到您的错误处理器.

否则,您可以自定义每条路线,将相同的选项传递到 `circuitBreaker` 工具栏 :

```js
fastify.circuitBreaker({
  threshold: 3, // default 5
  timeout: 5000, // default 10000
  resetTimeout: 5000 // default 10000
})
```

如果将选项直接传递给工具,则它优先于全局配置.

### 自定义错误消息

如果需要, 您可以更改默认错误消息 _电路打开出错_ 编辑 _超时出错_数字 :

```js
fastify.register(require('@fastify/circuit-breaker'), {
  timeoutErrorMessage: 'Ronf...', // default 'Timeout'
  circuitOpenErrorMessage: 'Oh gosh!' // default 'Circuit open'
})
```

## 洞穴

由于无法应用模式的经典超时功能,在此情况下,超时将测量执行和 **一旦路线完成** 如果所花费的时间超过超时, 它会返回一个错误, 即使路线已经产生一个成功的响应.

如果您需要经典的断路器来包围 API 调用 [`easy-breaker`](https://github.com/delvedor/easy-breaker)。 。 。 .

## 承认

图片来源: [马丁·福勒](https://martinfowler.com/bliki/CircuitBreaker.html)。 。 。 .

## 许可证

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

## 常见问题

### @fastify/circuit-breaker 是什么？

低通航线断路器

### 如何安装 @fastify/circuit-breaker？

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

### @fastify/circuit-breaker 支持 TypeScript 吗？

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

### @fastify/circuit-breaker 支持 ESM 还是 CommonJS？

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

### @fastify/circuit-breaker 可以商用吗？

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

### @fastify/circuit-breaker 的下载量有多少？

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

### @fastify/circuit-breaker 还在维护吗？

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

