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;

posted @   天之草  阅读(650)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示