
FastAPI是什么?快速上手指南
因此,在設計 API 時,提早考慮 限流配置、CDN 緩存設置、返回 payload 壓縮 等關鍵環節,才能在滿足業務需求的同時保障系統可用性與安全性。
/batch
調用,一次性響應多項資源。與其讓客戶端發起十余次請求,不如在后端統一執行并合并結果,顯著減少網絡往返。fields
參數,讓調用方僅獲取所需字段(如 ?fields=id,name,updatedAt
),避免大對象帶來的帶寬開銷。將靜態或半靜態數據緩存在離用戶更近的節點,實現 API性能優化 的第一步。
public, max-age=300, s-maxage=600
,既利用瀏覽器緩存,又讓 CDN 節點緩存更久。后端常用 Redis、Memcached 等內存緩存方案,將熱點數據緩存在本地:
// Node.js + Redis 簡單示例
async function getUserProfile(id) {
const cacheKey = `user:profile:${id}`;
let data = await redis.get(cacheKey);
if (data) return JSON.parse(data);
data = await db.query('SELECT * FROM user WHERE id = ?', [id]);
await redis.set(cacheKey, JSON.stringify(data), 'EX', 300);
return data;
}
通過上述模式,頻繁請求命中率可達 80% 以上,極大提升吞吐。
對 HTTP 響應啟用 gzip 或 Brotli 壓縮,可將 payload 大小減少 70% 以上。
Nginx 中開啟:
gzip on;
gzip_types application/json text/plain;
gzip_min_length 1024;
將耗時任務異步化,比如文件上傳后的縮略圖生成、日志寫入、短信推送等:
// 使用 Bull 隊列
uploadQueue.add({ filePath: req.file.path });
res.status(202).send({ message: '任務已入隊,正在處理' });
通過異步方式,主 API 能迅速返回,同時提升系統的并發處理能力。
在生產環境中,推薦引入云廠商或第三方的 WAF(Web Application Firewall)與 API網關實戰 組件:
使用框架內置或第三方校驗庫,對路徑參數、查詢參數、請求體做白名單校驗,避免 SQL 注入、XSS 等風險。例如,Node.js 推薦使用 Joi 或 class-validator。
// NestJS 示例
@Post()
create(@Body(new ValidationPipe({ whitelist: true })) dto: CreateUserDto) { … }
為所有 API 啟用 HTTPS,禁用過期或弱加密套件,使用 TLS 1.2+ 協議。對敏感字段(如用戶密碼、支付憑證)在應用層或數據庫層再做一次加密存儲。
以下示例展示如何在 Nginx 層實現 限流配置、緩存與鑒權結合的全流量管控:
http {
lua_shared_dict rate_limit 10m;
proxy_cache_path /data/cache levels=1:2 keys_zone=api_cache:100m max_size=1g inactive=10m;
server {
listen 443 ssl;
ssl_certificate cert.pem;
ssl_certificate_key key.pem;
location /api/ {
access_by_lua_block {
local limit_req = require "resty.limit.req"
local lim, err = limit_req.new("rate_limit", 200, 400)
if not lim then
ngx.log(ngx.ERR, "limit error: ", err)
return ngx.exit(500)
end
local key = ngx.var.binary_remote_addr
local delay, err = lim:incoming(key, true)
if not delay then
return ngx.exit(503)
end
if delay > 0 then
ngx.sleep(delay)
end
}
proxy_cache api_cache;
proxy_cache_valid 200 5m;
proxy_cache_use_stale error timeout updating;
proxy_pass http://backend_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Authorization $http_authorization;
proxy_set_header Accept-Encoding "";
}
}
}