## 性能(Fastify)
在底層,`Nest` 使用了[Express](https://expressjs.com/)框架,但如前所述,它提供了與各種其他庫的兼容性,例如 [Fastify](https://github.com/fastify/fastify)。`Nest`應用一個框架適配器,其主要功能是代理中間件和處理器到適當的特定庫應用中,從而達到框架的獨立性。
> 注意要應用框架適配器,目標庫必須提供在`Express` 類似的請求/響應管道處理
`Fastify` 非常適合這里,因為它以與 `express` 類似的方式解決設計問題。然而,`fastify` 的速度要快得多,達到了幾乎兩倍的基準測試結果。問題是,為什么 `Nest` 仍然使用 `express` 作為默認的 HTTP 提供程序?因為 `express` 是應用廣泛、廣為人知的,而且擁有一套龐大的兼容中間件。
但是由于 `Nest` 提供了框架獨立性,因此您可以輕松地在它們之間遷移。當您對快速的性能給予很高的評價時,`Fastify` 可能是更好的選擇。要使用 `Fastify`,只需選擇 `FastifyAdapter`本章所示的內置功能。
### 安裝
首先,我們需要安裝所需的軟件包:
```bash
$ npm i --save @nestjs/platform-fastify
```
### 適配器(Adapter)
安裝 fastify 后,我們可以使用 `FastifyAdapter`。
>main.ts
```typescript
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { ApplicationModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(ApplicationModule, new FastifyAdapter());
await app.listen(3000);
}
bootstrap();
```
默認情況下,`Fastify`僅在 `localhost 127.0.0.1` 接口上監聽(了解[更多](https://www.fastify.io/docs/latest/Getting-Started/#your-first-server)信息)。如果要接受其他主機上的連接,則應`'0.0.0.0'`在 `listen()` 呼叫中指定:
```typescript
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(ApplicationModule, new FastifyAdapter());
await app.listen(3000, '0.0.0.0');
}
```
### 平臺特定的軟件包
請記住,當您使用 `FastifyAdapter` 時,`Nest` 使用 `Fastify` 作為 `HTTP` 提供程序。 這意味著依賴 `Express` 的每個配方都可能不再起作用。 您應該改為使用 `Fastify` 等效程序包。
### 重定向響應
`Fastify` 處理重定向響應的方式與 `Express` 有所不同。要使用 `Fastify` 進行正確的重定向,請同時返回狀態代碼和 `URL`,如下所示:
```typescript
@Get()
index(@Res() res) {
res.status(302).redirect('/login');
}
```
### Fastify 選項
您可以通過構造函數將選項傳遞給 `Fastify`的構造 `FastifyAdapter` 函數。例如:
```typescript
new FastifyAdapter({ logger: true });
```
### 例子
[這里](https://github.com/nestjs/nest/tree/master/sample/10-fastify)有一個工作示例
- 介紹
- 概述
- 第一步
- 控制器
- 提供者
- 模塊
- 中間件
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 自定義裝飾器
- 基礎知識
- 自定義提供者
- 異步提供者
- 動態模塊
- 注入作用域
- 循環依賴
- 模塊參考
- 懶加載模塊
- 應用上下文
- 生命周期事件
- 跨平臺
- 測試
- 技術
- 數據庫
- Mongo
- 配置
- 驗證
- 緩存
- 序列化
- 版本控制
- 定時任務
- 隊列
- 日志
- Cookies
- 事件
- 壓縮
- 文件上傳
- 流式處理文件
- HTTP模塊
- Session(會話)
- MVC
- 性能(Fastify)
- 服務器端事件發送
- 安全
- 認證(Authentication)
- 授權(Authorization)
- 加密和散列
- Helmet
- CORS(跨域請求)
- CSRF保護
- 限速
- GraphQL
- 快速開始
- 解析器(resolvers)
- 變更(Mutations)
- 訂閱(Subscriptions)
- 標量(Scalars)
- 指令(directives)
- 接口(Interfaces)
- 聯合類型
- 枚舉(Enums)
- 字段中間件
- 映射類型
- 插件
- 復雜性
- 擴展
- CLI插件
- 生成SDL
- 其他功能
- 聯合服務
- 遷移指南
- Websocket
- 網關
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 適配器
- 微服務
- 概述
- Redis
- MQTT
- NATS
- RabbitMQ
- Kafka
- gRPC
- 自定義傳輸器
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 獨立應用
- Cli
- 概述
- 工作空間
- 庫
- 用法
- 腳本
- Openapi
- 介紹
- 類型和參數
- 操作
- 安全
- 映射類型
- 裝飾器
- CLI插件
- 其他特性
- 遷移指南
- 秘籍
- CRUD 生成器
- 熱重載
- MikroORM
- TypeORM
- Mongoose
- 序列化
- 路由模塊
- Swagger
- 健康檢查
- CQRS
- 文檔
- Prisma
- 靜態服務
- Nest Commander
- 問答
- Serverless
- HTTP 適配器
- 全局路由前綴
- 混合應用
- HTTPS 和多服務器
- 請求生命周期
- 常見錯誤
- 實例
- 遷移指南
- 發現
- 誰在使用Nest?