Fastify简介 #

一、什么是Fastify #

Fastify是一个高度专注于以最佳体验为开发者提供最低开销和强大插件架构的Web框架。它由Node.js核心贡献者Matteo Collina等人创建,深受Hapi和Express的启发。

1.1 核心定位 #

text
Fastify = 高性能 + 插件架构 + 开发者友好

Fastify的核心设计理念:

  • 高性能:尽可能低的性能开销
  • 可扩展:完善的插件系统,一切皆插件
  • 开发友好:详细的文档和错误提示

1.2 核心特点 #

特点 说明
极致性能 每秒可处理数万请求,比Express快2倍
插件系统 完善的插件架构,易于扩展
Schema验证 内置JSON Schema验证,自动优化性能
日志系统 极低开销的日志,使用Pino
TypeScript 一流的TypeScript支持
开发友好 详细的错误提示和文档

二、核心概念 #

2.1 为什么Fastify更快 #

Fastify的高性能来源于多个优化:

text
┌─────────────────────────────────────┐
│           Fastify 性能优化          │
├─────────────────────────────────────┤
│  1. 高效的路由匹配算法              │
│  2. JSON Schema 验证优化            │
│  3. 快速的 JSON 序列化              │
│  4. 极低开销的日志系统              │
│  5. 避免不必要的对象创建            │
└─────────────────────────────────────┘

路由优化示例

javascript
const fastify = require('fastify')()

fastify.get('/user/:id', {
  schema: {
    params: {
      id: { type: 'integer' }
    }
  }
}, async (request, reply) => {
  return { id: request.params.id }
})

2.2 插件系统 #

Fastify的插件系统是其核心特性:

javascript
const fastify = require('fastify')()

fastify.register(require('@fastify/cors'))
fastify.register(require('@fastify/helmet'))
fastify.register(require('@fastify/jwt'), {
  secret: 'supersecret'
})

fastify.register(async function (fastify, opts) {
  fastify.get('/plugin', async (request, reply) => {
    return { message: 'From plugin!' }
  })
})

2.3 Schema验证 #

Fastify内置JSON Schema验证:

javascript
fastify.post('/user', {
  schema: {
    body: {
      type: 'object',
      properties: {
        name: { type: 'string' },
        email: { type: 'string', format: 'email' },
        age: { type: 'integer', minimum: 0 }
      },
      required: ['name', 'email']
    },
    response: {
      200: {
        type: 'object',
        properties: {
          id: { type: 'integer' },
          name: { type: 'string' }
        }
      }
    }
  }
}, async (request, reply) => {
  return { id: 1, name: request.body.name }
})

2.4 生命周期 #

Fastify有完整的请求生命周期:

text
Incoming Request
       │
       ▼
┌─────────────────┐
│   onRequest     │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  preParsing     │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│   parsing       │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ preValidation   │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ preSerialization│
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  onSend         │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  onResponse     │
└────────┬────────┘
         │
         ▼
    Response Sent

三、Fastify vs Express #

3.1 性能对比 #

指标 Fastify Express
请求/秒 ~80,000 ~35,000
延迟 ~1.2ms ~2.8ms
吞吐量 中等

3.2 功能对比 #

功能 Fastify Express
内置验证 JSON Schema 需要中间件
日志系统 内置Pino 需要morgan
插件系统 完善 中间件模式
TypeScript 一流支持 需要额外配置
异步支持 原生async/await 需要包装

3.3 代码对比 #

Express写法

javascript
const express = require('express')
const bodyParser = require('body-parser')
const app = express()

app.use(bodyParser.json())

app.post('/user', (req, res) => {
  if (!req.body.name) {
    return res.status(400).json({ error: 'Name required' })
  }
  res.json({ id: 1, name: req.body.name })
})

app.listen(3000)

Fastify写法

javascript
const fastify = require('fastify')({ logger: true })

fastify.post('/user', {
  schema: {
    body: {
      type: 'object',
      required: ['name'],
      properties: {
        name: { type: 'string' }
      }
    }
  }
}, async (request, reply) => {
  return { id: 1, name: request.body.name }
})

fastify.listen({ port: 3000 })

四、应用场景 #

4.1 高性能API服务 #

Fastify非常适合构建高性能API:

text
适用场景
- 高并发API网关
- 微服务后端
- 实时数据处理
- 大流量Web服务

4.2 企业级应用 #

Fastify的插件系统适合企业级应用:

javascript
const fastify = require('fastify')()

fastify.register(require('./plugins/database'))
fastify.register(require('./plugins/auth'))
fastify.register(require('./plugins/cache'))

fastify.register(require('./routes/users'))
fastify.register(require('./routes/products'))

4.3 Serverless #

Fastify在Serverless环境表现优异:

javascript
const fastify = require('fastify')()

fastify.get('/', async (request, reply) => {
  return { hello: 'world' }
})

module.exports = async (req, res) => {
  await fastify.ready()
  fastify.server.emit('request', req, res)
}

五、生态系统 #

5.1 核心插件 #

插件 功能
@fastify/cors CORS支持
@fastify/helmet 安全头设置
@fastify/jwt JWT认证
@fastify/cookie Cookie处理
@fastify/session 会话管理
@fastify/static 静态文件服务
@fastify/multipart 文件上传
@fastify/rate-limit 请求限流
@fastify/swagger API文档生成

5.2 数据库插件 #

插件 数据库
@fastify/mongodb MongoDB
@fastify/postgres PostgreSQL
@fastify/redis Redis
fastify-typeorm TypeORM
fastify-sequelize Sequelize
fastify-prisma Prisma

六、版本演进 #

版本 发布年份 重要特性
Fastify 1.0 2018 首个稳定版本
Fastify 2.0 2019 改进的插件系统
Fastify 3.0 2020 新的序列化系统
Fastify 4.0 2022 异步监听、改进的类型支持
Fastify 5.0 2024 性能优化、新特性

七、学习路线 #

text
基础阶段
├── Fastify基础语法
├── 路由系统
├── 请求与响应
└── 数据验证

进阶阶段
├── 插件系统
├── 中间件与钩子
├── 错误处理
└── 日志系统

高级阶段
├── 性能优化
├── 自定义插件
├── TypeScript集成
└── 部署与监控

八、总结 #

Fastify是一个优秀的Node.js Web框架:

  • 高性能:极致的性能优化
  • 可扩展:完善的插件系统
  • 开发友好:详细的文档和错误提示
  • 现代化:原生支持async/await

选择Fastify的理由:

  • 需要高性能API服务
  • 喜欢插件化架构
  • 需要内置的数据验证
  • 想要更好的TypeScript支持
  • 追求现代化的开发体验

准备好开始学习Fastify了吗?让我们进入下一章,学习如何安装Fastify环境!

最后更新:2026-03-28