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 @ 2022-05-26 00:12  天之草  阅读(630)  评论(0编辑  收藏  举报