基于 Express.js 的幂等键中间件实现,确保重复请求不会产生重复副作用。
幂等性是指同一个请求执行一次和执行多次的效果相同。在 HTTP API 中,GET、PUT、DELETE 等方法天然幂等,但 POST 方法不是。使用幂等键(Idempotency Key)可以让 POST 请求也具备幂等性:客户端在请求头中携带唯一的 Idempotency-Key,服务器缓存该键对应的响应,重复请求直接返回缓存结果。
Idempotency-Key 请求头的幂等性保证npm install
npm start
服务器将在 http://localhost:3000 启动。
首次请求:
curl -X POST http://localhost:3000/api/orders \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-$(date +%s)" \
-d '{"customerId":"cust-1","items":[{"productId":"prod-1","quantity":2,"price":25}]}'
重复使用相同的 Idempotency-Key 发送请求,将返回第一次的结果,不会重复创建订单。响应会包含 X-Idempotency-Replay: true 头标识这是重放响应。
GET /api/orders - 列出所有订单GET /api/orders/:id - 按 ID 查询订单GET /health - 健康检查npm test
src/
├── server.js # Express 服务器入口
├── idempotency.js # 幂等键中间件实现
└── routes/
└── orders.js # 订单路由
tests/
└── test-idempotency.js # 幂等性测试用例