Skip to content

Node.js 网关层(Gateway)

网关层是客户端和后端服务之间的中间层,统一处理路由转发、负载均衡、安全加密等横切关注点。技术选型推荐 Fastify(性能最高)。

网关六⼤功能

功能说明
路由URL → 转发到对应后端服务
负载均衡多实例分发热度请求
缓存缓存常见响应,减轻后端压力
信道加密SSL/TLS 终止,保护传输安全
熔断后端服务故障时自动切断
限流防止某用户/某服务过载(之前学的限流阀)

架构图

客户端 → 网关层(fastify)
           ├─ /api/user/*  →  user-service:3001
           ├─ /api/order/* →  order-service:3002
           └─ /static/*    →  CDN / OSS

Fastify 网关实现

js
import Fastify from 'fastify'
import proxy from '@fastify/http-proxy'

const gateway = Fastify({ logger: true })

// 注册代理
gateway.register(proxy, {
  upstream: 'http://localhost:3001',
  prefix: '/api/user',
  rewritePrefix: '/user'   // /api/user/profile → /user/profile
})

gateway.register(proxy, {
  upstream: 'http://localhost:3002',
  prefix: '/api/order',
  rewritePrefix: '/order'
})

gateway.listen({ port: 80 })

可以集成的能力

所有之前章节学到的技术都可以挂载到网关层:

  • JWT 验证onRequest 钩子统一校验
  • 限流阀 → Redis + Lua 脚本
  • CORS@fastify/cors
  • 日志 → Fastify 内置 Pino 日志
  • 压缩@fastify/compress(Gzip)