第 08 章:服务端框架与企业级生态
大约 3 分钟
第 08 章:服务端框架与企业级生态
Node.js 生态拥有丰富且成熟的服务端框架。从轻量级的 Express/Koa 到企业级的 NestJS 与极速的 Fastify,理解其架构设计对于构建高性能 API 至关重要。
1. 基础 Web 框架 (Express vs Koa)
1.1 Express 线性中间件
Express 采用线性中间件流水线。每个中间件调用 next() 后,下一个中间件接着执行,但它对异步 Promise 的级联支持并不天然友好。
1.2 Koa 异步洋葱圈模型 (Onion Model)
Koa 核心机制是基于 async/await 实现的洋葱圈模型。请求从最外层中间件进入,逐层深入,遇到 await next() 暂停并进入内层,当最内层逻辑处理完毕后,再由内向外依次退回执行 next() 后的逻辑。
请求进入 ───> [中间件 1 (前置)] ───> [中间件 2 (前置)] ───> [路由处理]
│
响应返回 <─── [中间件 1 (后置)] <─── [中间件 2 (后置)] <───────┘手写简易 Koa 核心中间件合成函数 (compose):
function compose(middlewares) {
return function (context, next) {
let index = -1;
return dispatch(0);
function dispatch(i) {
if (i <= index) return Promise.reject(new Error('next() 被重复调用多次!'));
index = i;
let fn = middlewares[i];
if (i === middlewares.length) fn = next;
if (!fn) return Promise.resolve();
try {
// 将下一个中间件递归包装为 Promise 传递给当前中间件的 next 参数
return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
} catch (err) {
return Promise.reject(err);
}
}
};
}
// 模拟测试
const middlewares = [
async (ctx, next) => {
console.log('1. 洋葱最外层 - 开始');
await next();
console.log('5. 洋葱最外层 - 结束');
},
async (ctx, next) => {
console.log('2. 中间层 - 开始');
await next();
console.log('4. 中间层 - 结束');
},
async (ctx, next) => {
console.log('3. 核心业务处理');
}
];
compose(middlewares)({});
/* 输出顺序:
1. 洋葱最外层 - 开始
2. 中间层 - 开始
3. 核心业务处理
4. 中间层 - 结束
5. 洋葱最外层 - 结束
*/2. 企业级与高性能框架 (NestJS & Fastify)
2.1 NestJS 依赖注入与 IoC 容器
NestJS 是借鉴 Angular 体系设计的企业级 TypeScript 框架。它提供了规范的 IoC (Inversion of Control 控制反转) 容器与 DI (Dependency Injection 依赖注入) 机制:
// user.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class UserService {
async getUser(id: string) {
return { id, name: 'Alice', role: 'admin' };
}
}
// user.controller.ts
import { Controller, Get, Param } from '@nestjs/common';
import { UserService } from './user.service';
@Controller('users')
export class UserController {
// IoC 容器自动进行依赖注入,无需手动 new UserService()
constructor(private readonly userService: UserService) {}
@Get(':id')
async findOne(@Param('id') id: string) {
return this.userService.getUser(id);
}
}2.2 Fastify 预编译 JSON 优化原理
Fastify 性能大幅超越 Express 的秘诀在于:它使用 fast-json-stringify 结合 JSON Schema 预编译 技术。传统 JSON.stringify 需要在运行时递归遍历对象数据类型,而 Fastify 预先根据 JSON Schema 编译好了固定的字符串拼接代码,极大减少了序列化开销。
3. 全栈、BFF 架构与持久化存储
3.1 BFF (Backend For Frontend) 网关设计
BFF 架构通过 Node.js 作为中间层服务,负责向下聚合微服务接口,向上为移动端、Web 端定制剪裁字段:
[前端 APP / Web]
│
▼ (GraphQL 或 RESTful 剪裁请求)
[Node.js BFF 聚合层]
├── 校验 Token / 权限
├── 并发请求微服务
└── 拼装结构并剪裁多余字段
├──> [用户微服务]
├──> [订单微服务]
└──> [推荐微服务]3.2 ORM/ODM 与 Redis 数据库实战
在 Node.js 中访问关系型数据库,主流 ORM 库如 Prisma 提供了极佳的类型安全:
// 使用 Prisma ORM 访问 PostgreSQL / MySQL
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function createOrderWithUser(userId: string, amount: number) {
// 开启事务处理
return await prisma.$transaction(async (tx) => {
const order = await tx.order.create({
data: { userId, amount, status: 'PAID' }
});
await tx.user.update({
where: { id: userId },
data: { balance: { decrement: amount } }
});
return order;
});
}Redis 缓存读写与连接池管理:
const Redis = require('ioredis');
const redis = new Redis({ host: '127.0.0.1', port: 6379, maxRetriesPerRequest: 3 });
async function getCachedUser(userId) {
const cacheKey = `user:${userId}`;
// 1. 先查 Redis 缓存
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
// 2. 缓存未命中,查数据库
const user = await fetchUserFromDb(userId);
// 3. 写入缓存并设置 5 分钟过期时间 (防止缓存雪崩,可加随机 jitter)
await redis.set(cacheKey, JSON.stringify(user), 'EX', 300);
return user;
}