第6章:批量操作(Batch Operations)
一、导读
1.1 本章学习目标
第6章讲解批量操作模式——一次处理多个资源。
本章的核心学习目标包括:
- 掌握批量 CRUD 的设计
- 理解事务性批量操作
- 学会设计高效的批量 API
1.2 为什么本章如此重要
逐个操作多个资源效率低下。批量操作减少网络往返,提高吞吐量。
1.3 核心问题引导
批量操作应该支持哪些操作?
批量操作是事务性的还是部分成功的?
如何报告批量操作中每个子操作的结果?
批量操作的大小限制如何设计?
二、核心概念详解
2.1 批量创建
POST /api/v1/users:batchCreate
{
"requests": [
{
"name": "Alice",
"email": "alice@example.com"
},
{
"name": "Bob",
"email": "bob@example.com"
}
]
}
→ 200 OK
{
"results": [
{
"status": "SUCCESS",
"resource": {"id": "usr_1", "name": "Alice", ...}
},
{
"status": "SUCCESS",
"resource": {"id": "usr_2", "name": "Bob", ...}
}
]
}2.2 批量更新
POST /api/v1/users:batchUpdate
{
"requests": [
{
"id": "usr_1",
"update": {"name": "Alice Smith"}
},
{
"id": "usr_2",
"update": {"name": "Bob Jones"}
}
]
}2.3 批量删除
POST /api/v1/users:batchDelete
{
"ids": ["usr_1", "usr_2", "usr_3"]
}
→ 200 OK
{
"results": [
{"id": "usr_1", "status": "DELETED"},
{"id": "usr_2", "status": "DELETED"},
{"id": "usr_3", "status": "NOT_FOUND"}
]
}2.4 事务性批量
// 原子性批量操作
POST /api/v1/orders:batchCreate
{
"requests": [...],
"transactional": true // 全部成功或全部失败
}
// 非事务性:部分成功
POST /api/v1/orders:batchCreate
{
"requests": [...],
"transactional": false // 每个独立处理
}三、实战案例
3.1 案例一:批量导入 API
POST /api/v1/products:batchCreate
{
"requests": [
{"name": "Product A", "price": 29.99},
{"name": "Product B", "price": 49.99},
{"name": "", "price": 19.99} // 验证失败
]
}
→ 200 OK
{
"results": [
{"status": "SUCCESS", "resource": {"id": "prod_1", ...}},
{"status": "SUCCESS", "resource": {"id": "prod_2", ...}},
{"status": "FAILED", "error": {"code": "VALIDATION_ERROR", "message": "Name is required"}}
],
"summary": {
"total": 3,
"succeeded": 2,
"failed": 1
}
}四、本章小结
批量 CRUD:batchCreate、batchUpdate、batchDelete。
事务性:全部成功或全部失败 vs 部分成功。
结果报告:每个子操作独立报告状态。
五、思考与练习
设计一个批量订单 API。
批量操作的大小限制应该如何确定?
如何处理批量操作中的部分失败?