Spring Boot + Vue 3 并发编辑:乐观锁版本号、If-Match 与 409 冲突处理
Spring Boot + Vue 3 并发编辑:乐观锁版本号、If-Match 与 409 冲突处理
两个人同时打开同一条订单:A 改了备注并保存,B 的页面还停留在旧数据上,改完金额一点保存,A 刚写的备注没了。这类问题的标准名字叫 lost update,RFC 6585 在定义 428 状态码时专门描述了它。解决它有三层可用手段——数据库锁、版本号、HTTP 条件请求,但它们的作用范围完全不同。最容易踩的一个坑是:在 Spring Boot 里加了 ShallowEtagHeaderFilter,以为并发冲突就有保障了,实际上这个 filter 连 If-Match 都不处理。这一篇按官方规范和 javadoc 把边界划清楚,再给出前后端能落地的一套做法。
一、丢失更新发生在哪一步
读、改、写是三次独立操作,中间隔着人在页面上编辑的时间。
A:GET /orders/7 → version=3 ──┐
│ 两个人各自编辑
B:GET /orders/7 → version=3 ──┘
│ │
▼ ▼
A:PUT(备注="加急", version=3)──▶ version 变 4,备注写入
│
B:PUT(金额=500, version=3)────────▶ 若不做校验,直接覆盖整行
▼
备注回到旧值,A 的修改丢失
RFC 6585 §3 的原文描述得很准:"a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict." 注意这里丢的是别人已经提交的改动,不是自己这次有没有成功——B 的请求会返回 200,界面显示"保存成功",问题要等到别人回头看才发现。
二、三条防线各管一段
| 手段 | 作用层 | 拦截时机 | 代价 |
|---|---|---|---|
悲观锁(SELECT ... FOR UPDATE) |
数据库 | 读取时就占住行 | 长事务、死锁风险、编辑期间一直持锁,不适合人参与的长表单 |
| 乐观锁(version 字段) | 数据库 / ORM | UPDATE 的 WHERE 条件 | 冲突时请求失败,需要前端提示与重试策略 |
| HTTP 条件请求(ETag + If-Match) | 协议 / 应用层 | 进入业务方法之前 | 要处理 412/428、跨域请求头、前端保存冲突时的交互 |
实际项目里通常叠用两层:HTTP 层用 If-Match 把明显过期的请求挡在门外,数据库层用 version 兜住"两个请求几乎同时到达"的竞态。只做前一层挡不住并发瞬间,只做后一层则所有冲突都要等到 SQL 执行完才知道。
三、ETag 是响应头,If-Match 是请求头
RFC 9110 §8.8.3 对 ETag 的定义:它是响应里的 "current entity tag for the selected representation",是"an opaque validator for differentiating between multiple representations of the same resource"。它由一段带引号的不透明字符串组成,"possibly prefixed by a weakness indicator",也就是 W/。
同一节 §8.8.3.2 定义了两种比较函数:
"Strong comparison": two entity tags are equivalent if both are not weak and their opaque-tags match character-by-character. "Weak comparison": two entity tags are equivalent if their opaque-tags match character-by-character, regardless of either or both being tagged as "weak".
规范给出的对照表:
| ETag 1 | ETag 2 | 强比较 | 弱比较 |
|---|---|---|---|
W/"1" |
W/"1" |
不匹配 | 匹配 |
W/"1" |
W/"2" |
不匹配 | 不匹配 |
W/"1" |
"1" |
不匹配 | 匹配 |
"1" |
"1" |
匹配 | 匹配 |
§13.1.1 对 If-Match 的要求很硬:"An origin server MUST use the strong comparison function when comparing entity tags for If-Match",理由是客户端用这个前置条件就是想阻止在表示数据有任何变化时执行方法。所以拿一个弱 ETag(W/...)去做并发控制,语义上就不成立。
求值规则同样是明确的:
- 值是
*:只要目标资源当前存在表示,条件为真。 - 值是一串 entity tag:任意一个与当前表示的 entity tag 匹配即为真。
- 其他情况为假。
- "the origin server MUST evaluate the If-Match condition per Section 13.2 prior to performing the method",条件为假时 "MUST NOT perform the requested method"。
这里藏着一个少有人注意的分支:条件为假时通常响应 412,但规范允许另一种处理——如果这个状态变更看起来已经生效过(比如上一次响应丢了、或别的客户端做了等价修改),源服务器 "MAY respond with a 2xx (Successful) status code"。规范紧接着警告,对把公共资源当信号量用、做非原子增量这类场景,"an origin server is better off being stringent",否则会丢掉重要的状态迁移。做业务系统时,别照搬这个 2xx 的宽松选项。
§13.2.2 还规定了多个条件头同时出现时的顺序:If-Match 排第一,为假时响应 412;之后才是 If-Unmodified-Since、If-None-Match 等。理由是 "lost update preconditions have more strict requirements than cache validation"。
四、412、409、428 分别站在什么位置
| 状态码 | 出处 | 含义 | 适合怎么用 |
|---|---|---|---|
| 412 Precondition Failed | RFC 9110 §15.5.13 | "one or more conditions given in the request header fields evaluated to false when tested on the server" | 带了 If-Match 但版本不匹配,方法未执行 |
| 409 Conflict | RFC 9110 §15.5.10 | 请求因与目标资源当前状态冲突而无法完成,"The user might be able to resolve the conflict and resubmit" | 版本号放在请求体里、由数据库层检测到冲突 |
| 428 Precondition Required | RFC 6585 §3 | "the origin server requires the request to be conditional" | 请求根本没带条件,服务端拒绝执行并要求补上 |
409 的定义里有一句对前端很关键的 SHOULD:"The server SHOULD generate content that includes enough information for a user to recognize the source of the conflict." 也就是说只回一个 409 加一句"冲突了"不够,最好把服务端当前值一起带回去,用户才能决定是覆盖、放弃还是合并。
428 的三条附加事实也别漏:典型用途就是避免 lost update;响应 "SHOULD explain how to resubmit the request successfully",RFC 给的例子里直接写了 try using "If-Match";"Responses with the 428 status code MUST NOT be stored by a cache"。更重要的是 §7.1 的安全考虑:"The 428 status code is optional; clients cannot rely upon its use to prevent 'lost update' conflicts." 它是提示,不是防线——客户端不主动带 If-Match,服务端该拒还是得拒。
五、ShallowEtagHeaderFilter 不是并发保护
这是全篇最容易搞错的地方。Spring 里确实有个开箱即用的 ETag filter,很多人注册完就以为条件请求自动生效了。看 javadoc 原文:
Filterthat generates anETagvalue based on the content on the response. This ETag is compared to theIf-None-Matchheader of the request. If these headers are equal, the response content is not sent, but rather a304 "Not Modified"status instead.
Since the ETag is based on the response content, the response (for example, a
View) is still rendered. As such, this filter only saves bandwidth, not server performance.
State-changing HTTP methods and other HTTP conditional request headers such as
If-MatchandIf-Unmodified-Sinceare outside the scope of this filter. Please consider usingServletWebRequest.checkNotModified(String, long)instead.
三句话把边界说死了:
| 能做 | 不能做 |
|---|---|
| 基于响应内容生成 ETag | 不处理 If-Match |
比对 If-None-Match,命中返回 304 |
不覆盖 POST / PUT / DELETE 这类状态变更方法 |
| 省下响应体传输的带宽 | 不省服务端渲染、查询、计算(响应照样生成) |
再看几个实现细节,都来自同一个 javadoc:
generateETagHeaderValue的默认实现 "generates an MD5 hash",算的是响应 body 字节。isEligibleForEtag默认只在四个条件同时满足时返回 true:响应尚未提交、状态码是 2xx、请求方法是 GET、Cache-Control不含no-store。setWriteWeakETag(boolean)决定写出的是不是弱 ETag;结合第三节的强比较规则,弱 ETag 本来就做不了If-Match。disableContentCaching(request)用于流式响应,且 "must be called before the response is written to"。shouldNotFilterAsyncDispatch()默认false,为了让 filter 延迟到最后一次异步 dispatch 再生成 ETag。
结论:这个 filter 是响应缓存优化,和并发编辑没有关系。它连状态变更方法都不碰,更不会拦下一次覆盖写。
六、条件写入该走哪条路
ShallowEtagHeaderFilter 的 javadoc 自己给出了替代建议:ServletWebRequest.checkNotModified(...)。它的 javadoc 明确写着:"This method works with conditional GET/HEAD requests, but also with conditional POST/PUT/DELETE requests.";checkNotModified(String etag) 会"transparently set the ETag response header and HTTP status when applicable",传进去的 etag "will be padded with quotes (") if necessary";想同时强制强 ETag 与 Last-Modified,用 checkNotModified(String, long)。
但业务系统通常还需要自定义响应体——409 要带服务端当前值,428 要说明怎么重提交,这些都不是 304 能表达的。更直接的做法是自己读 If-Match 并比对版本号:
@RestController
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
@PutMapping("/orders/{id}")
public ResponseEntity<?> update(@PathVariable Long id,
@RequestHeader(value = "If-Match", required = false) String ifMatch,
@RequestBody OrderEditCmd cmd) {
// 没带条件就拒,RFC 6585 要求响应说明如何重提交
if (ifMatch == null || ifMatch.isBlank()) {
// 简化示意:实际按 RFC 9457 返回 ProblemDetail,说明如何重提交
return ResponseEntity.status(428)
.body(Map.of("detail", "该接口要求条件请求,请携带 If-Match"));
}
Order current = orderService.get(id);
String currentTag = "\"" + current.getVersion() + "\""; // 强 ETag,不带 W/
if (!matchesStrong(ifMatch, currentTag)) { // 应用自定义:处理 * 与列表,只做强比较
ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.PRECONDITION_FAILED);
problem.setTitle("数据已被他人修改");
problem.setProperty("current", current); // 交给前端展示差异
return ResponseEntity.status(HttpStatus.PRECONDITION_FAILED).body(problem);
}
return ResponseEntity.ok(orderService.update(cmd));
}
}
matchesStrong 是应用自己实现的比对函数,按 §13.1.1 的规则处理 * 和逗号分隔的列表,且只做强比较。ProblemDetail 的用法在本系列 RFC 9457 那篇里讲过,扩展成员正好用来携带 current。这里返回 412 而不是 409,是因为冲突在方法执行前由请求头判定,语义上对得上 §15.5.13。
七、数据库层的版本号才是最后一道闸
HTTP 层挡得住"拿着旧页面点保存",挡不住两个请求几乎同时通过校验、随后并发执行 UPDATE。所以 version 条件必须落在 SQL 里。
MyBatis-Plus 的 OptimisticLockerInnerInterceptor 官方文档给出的实现原理是:读取时拿到 version,更新时把它一起传回去,SQL 里带上 version = oldVersion,并设置 version = newVersion;版本不匹配则更新失败。注意事项原文列得很具体:
| 项 | 官方说明 |
|---|---|
| 支持类型 | int、Integer、long、Long、Date、Timestamp、LocalDateTime |
| 整数版本 | newVersion 是 oldVersion + 1 |
| 回写 | newVersion 会自动回写到实体对象中 |
| 支持的方法 | updateById(entity)、update(entity, wrapper)、saveOrUpdate(entity)、insertOrUpdate(entity)(3.5.7+) |
| 自定义方法 | 参数形式与内置方法等价时也会填充乐观锁,"但更新实现需要自行处理" |
| 限制 | update(entity, wrapper) 中 wrapper 不能复用 |
配置两步:注册拦截器,在实体字段上加 @Version。注意这里用的是 com.baomidou.mybatisplus.annotation.Version,和 JPA 的 jakarta.persistence.Version 是两个不同的注解,别导错包。
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
public void update(OrderEditCmd cmd) {
Order entity = new Order();
entity.setId(cmd.getId());
entity.setAmount(cmd.getAmount());
entity.setRemark(cmd.getRemark());
entity.setVersion(cmd.getVersion()); // 必须是读取时的旧版本
int rows = orderMapper.updateById(entity);
if (rows == 0) {
// 版本不匹配时更新影响行数为 0,不能当成"没变化"忽略
throw new VersionConflictException(cmd.getId()); // 应用自定义异常,全局映射到 409
}
}
JPA 那条路径的表现不一样。Spring 的 ObjectOptimisticLockingFailureException javadoc 写的是 "Exception thrown on an optimistic locking violation for a mapped object. Provides information about the persistent class and the identifier.",它还有 getPersistentClass() / getIdentifier() 可以拿到冲突对象的信息,Spring Data JPA 侧的子类是 JpaOptimisticLockingFailureException。也就是说:
| ORM 路径 | 冲突表现 | 必须做的事 |
|---|---|---|
| MyBatis-Plus | updateById 返回 0 |
显式检查返回值并抛业务异常 |
| Spring Data JPA | 抛 ObjectOptimisticLockingFailureException |
全局异常处理器映射到 409,别让它变成 500 |
两个路径都要把冲突转成明确的 4xx,前端才有办法处理。若异常一路冒到容器变成 500,用户只会看到"系统错误",然后反复点保存。
八、version 放请求体还是放 If-Match 头
GET /orders/7
│ 响应:ETag: "3" ← 服务端给出当前版本
▼
前端编辑,把 "3" 存起来
│
PUT /orders/7
│ If-Match: "3" ← 或放在 body 的 version 字段
▼
服务端比对当前版本 ── 一致 ──▶ 执行更新,version 变 4
└─ 不一致 ──▶ 412(请求头)/ 409(请求体)
| 位置 | 好处 | 需要额外处理 |
|---|---|---|
请求体 version 字段 |
前端容易拿到和调试;和表单一起提交;不需要读响应头 | 每个接口自己约定字段名;语义不统一;冲突时习惯回 409 |
If-Match 请求头 |
HTTP 标准语义,代理和网关能识别;428 有明确的引导路径;与 412 天然对应 | 跨域时属于非简单请求头,需要 Access-Control-Allow-Headers 放行并会触发 preflight;前端还要能读到响应里的 ETag |
后一行有个很实际的坑。MDN 的 Access-Control-Expose-Headers 文档列出了默认对脚本可见的 CORS-safelisted response headers,只有 7 个:Cache-Control、Content-Language、Content-Length、Content-Type、Expires、Last-Modified、Pragma。ETag 不在其中。所以跨域部署时,即使服务端返回了 ETag,response.headers.get('ETag') 也拿不到,必须显式加:
Access-Control-Expose-Headers: ETag
Access-Control-Allow-Headers: Content-Type, If-Match, Idempotency-Key
MDN 还提醒一点:* 通配符"only counts as a special wildcard value for requests without credentials",带 Cookie 或 HTTP 认证信息的请求里,它只是字面量头名 *——本系列登录态篇讲 withCredentials 时遇到过同一类问题。如果站点用 Cookie 维持会话,别指望 Access-Control-Expose-Headers: * 能生效,老老实实列出 ETag。
不想处理这些的话,把 version 放进响应体和请求体是最省事的方案,代价是放弃 HTTP 条件请求的标准化语义。
九、前端拿到 409/412 之后该做什么
最重要的一条:不要静默自动重试。冲突意味着"你基于的旧数据已经不成立",拿同一个旧 version 重试一万次还是冲突;换成服务端最新 version 重试,等于悄悄覆盖别人刚写的内容,比丢失更新更糟。
import { ref, shallowRef } from 'vue';
/** 编辑页:保存冲突时把服务端当前值交给用户 */
export function useEditableOrder(load: (id: number) => Promise<OrderVO>,
save: (cmd: OrderEditCmd) => Promise<OrderVO>) {
const form = ref<OrderEditCmd | null>(null);
const version = ref(0);
const conflict = shallowRef<OrderVO | null>(null); // 服务端当前值
async function init(id: number) {
const data = await load(id);
form.value = { ...data };
version.value = data.version;
}
async function submit() {
if (!form.value) return;
try {
const saved = await save({ ...form.value, version: version.value });
version.value = saved.version; // 保存成功后更新本地版本
conflict.value = null;
} catch (err: unknown) {
// 按项目请求封装层的结构取出状态码,避免直接用 any
const e = err as { response?: { status?: number; data?: { current?: OrderVO } } };
const status = e?.response?.status;
if (status !== 409 && status !== 412) throw err;
conflict.value = e.response?.data?.current ?? null; // 展示差异
}
}
return { form, version, conflict, init, submit };
}
| 冲突处理策略 | 适用场景 | 问题 |
|---|---|---|
| 提示后让用户重新加载 | 字段少、改动小 | 用户已输入的内容会丢,体验差 |
| 展示服务端当前值 + 本地草稿,用户手动合并 | 通用,最稳妥 | 交互成本高,要写好差异展示 |
| 按字段自动合并(只提交用户改过的字段) | 大表单、多人分区域编辑 | 需要记录脏字段;同一字段被两人改仍要人工决策 |
| 静默以最新 version 重发 | 不建议 | 等于覆盖他人改动,且用户不知情 |
前三种都是工程上的取舍,Spring 和 HTTP 规范都不提供"自动合并"能力,别指望有个注解能解决。另外,保存成功后一定要把返回的 version 写回本地状态——否则用户连续保存第二次,手里的还是旧版本,会自己撞出一次冲突。
别把并发控制、幂等、事务混成一件事
这三个概念经常在同一段代码里出现,但拦的是三种完全不同的问题:
一次保存请求要分别过三关
① 幂等:这是不是同一笔提交的重发? → Idempotency-Key / 唯一索引
② 并发:我基于的版本还是最新的吗? → If-Match / version → 412 / 409
③ 原子:多个写操作能否一起成功或回滚? → @Transactional
│
▼
全部通过才落库;任一失败返回明确的 4xx 或回滚
| 关注点 | 拦的是什么 | 拦不住什么 |
|---|---|---|
| 幂等键 | 网络重试、用户连点造成的重复请求 | 两个不同用户基于不同目的同时编辑 |
| 乐观锁 | 拿着旧版本覆盖他人已提交的改动 | 同一次请求内部多个写操作的原子性 |
| 事务 | 部分写入、部分失败导致的数据不一致 | 跨请求的版本冲突(事务提交完冲突照样存在) |
所以三者是叠加关系,不是三选一。只加 @Transactional 不解决覆盖写,只加 Idempotency-Key 也不解决两个人同时编辑;本系列幂等篇和事务篇讲的是各自那一层,这一篇补的是②。
十、几个反复出现的误区
| 误区 | 为什么不对 |
|---|---|
用 update_time 时间戳当版本 |
同一毫秒内两次更新可能得到相同值;机器时钟调整也会让比较失效。递增整数或数据库生成的版本更可靠(工程判断,非规范要求) |
只加了 @Version 不检查返回值 |
MyBatis-Plus 路径下冲突表现为影响行数 0,不检查就等于没有保护 |
注册 ShallowEtagHeaderFilter 当并发控制 |
它只处理 If-None-Match / 304,官方明说 If-Match 与状态变更方法不在范围内 |
用弱 ETag 做 If-Match |
RFC 9110 要求 If-Match 必须用强比较,W/ 前缀直接不匹配 |
| 把 409 当网络错误自动重试 | 见第九节,冲突不是暂时性故障 |
跨域只读到 undefined 的 ETag |
ETag 不在 CORS 默认暴露的 7 个响应头里,需要 Access-Control-Expose-Headers |
| 把 version 交给前端但不校验 | 前端传来的任何值都是不可信输入,服务端必须以数据库当前值为准重新比对 |
最后一条尤其要强调:If-Match 和请求体里的 version 都来自客户端,服务端拿它们跟自己查出来的当前版本比对才有意义。直接把客户端传来的 version 写进 SET version = version + 1 而 WHERE 里不带旧版本条件,等于把锁交给了调用方。
十一、排查清单
| 现象 | 优先检查 | 验证方式 |
|---|---|---|
| 后保存的人覆盖了先保存的改动 | 更新 SQL 的 WHERE 是否带 version | 打开 SQL 日志看 WHERE ... AND version = ? |
加了 @Version 却没拦住 |
是否检查了影响行数;是不是导成了 JPA 的 @Version |
打印 updateById 返回值与实体类 import |
| 冲突时前端收到 500 | 全局异常处理器是否映射 ObjectOptimisticLockingFailureException |
对异常类型加断点或日志 |
| 加了 ETag filter 仍旧覆盖 | ShallowEtagHeaderFilter 不处理 If-Match |
确认是否自己实现了条件比对 |
| 跨域时前端拿不到 ETag | 缺少 Access-Control-Expose-Headers: ETag |
浏览器 Network 里看响应头与 preflight |
| 带 Cookie 时通配符暴露头不生效 | * 在带凭据请求里只是字面量 |
改成显式列出头名 |
| 第二次保存必定冲突 | 保存成功后没更新本地 version | 打印提交前后的 version 值 |
| 用户重复点保存产生两条记录 | 冲突处理和幂等是两件事 | 写接口另配 Idempotency-Key |
十二、收口
按层次看这件事就清楚了:HTTP 层用 ETag / If-Match 把明显过期的提交挡在方法执行之前,用 412、428 给出明确语义;数据库层用 version 条件更新兜住真正的同时写入,冲突转成 409 并带上服务端当前值;前端负责展示差异、让人决定怎么合并,而不是替用户悄悄重试。三者缺一层,都会留一个能覆盖别人数据的口子。