mysql的乐观锁处理
在事务里,为了实现乐观锁,不使用select for update, 而是在update 的时候,进行条件判断 where xxx= select的值
const (
casRetries = 3
casInterval = 50 * time.Millisecond
)
// 重试机制 + 乐观锁
for i := 0; i < casRetries; i++ {
if principal, err = in.ByfiRepo.UpdateConfirmDailyPnl(ctx, &byfirepo.UpdatePnlParams{
ProductType: productType,
LastDay: flexibleLastDay,
FlexibleSavingParams: pnlRecord,
}); err == nil {
break
}
time.Sleep(casInterval)
}
容易出现的坑:
1、当我们去update 某条语句时,假如条件不满足:
update wallets set available_balance_e8=available_balance_e8+144 where id=888888;
Rows matched: 0 Changed: 0 Warnings: 0
2、当我们去update 某条语句时,假如条件不满足:
update wallets set available_balance_e8=available_balance_e8+0 where id=1;
Rows matched: 1 Changed: 0 Warnings: 0
res, err1 := sql.Exec(ctx, tx)
if err1 != nil {
return err1
}
affected, err := res.RowsAffected()
if err != nil {
return err1
}
if affected == 0 {
return errors.New("cas error, need try again")
}
这个写法就有可能出问题,因为第二种情况,其实不算是错,而且我们可能在事务里确实需要用到,他能match,只是affected为0,但在这里
就是和第一种情况一样的当作错误去处理,就不对了
统计,coin=102,没有重复account_id的条数
select count(distinct account_id) from wallets where coin = 102;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!