前言
最近在用 Go
写业务的时碰到了并发更新数据的场景,因为该业务并发度不高,只是为了防止出现并发时数据异样。
所以天然就想到了乐观锁的解决方案。
实现
乐观锁的实现比较简单,置信大部分有数据库应用教训的都能想到。
UPDATE `table` SET `amount`=100,`version`=version+1 WHERE `version` = 1 AND `id` = 1
须要在表中新增一个相似于 version
的字段,实质上咱们只是执行这段 SQL
,在更新时比拟以后版本与数据库版本是否统一。
如上图所示:版本统一则更新胜利,并且将版本号+1;如果不统一则认为呈现并发抵触,更新失败。
这时能够间接返回失败,让业务重试;当然也能够再次获取最新数据进行更新尝试。
咱们应用的是 gorm
这个 orm
库,不过我查阅了官网文档却没有发现乐观锁相干的反对,看样子后续也不打算提供实现。
不过借助 gorm
实现也很简略:
type Optimistic struct { Id int64 `gorm:"column:id;primary_key;AUTO_INCREMENT" json:"id"` UserId string `gorm:"column:user_id;default:0;NOT NULL" json:"user_id"` // 用户ID Amount float32 `gorm:"column:amount;NOT NULL" json:"amount"` // 金额 Version int64 `gorm:"column:version;default:0;NOT NULL" json:"version"` // 版本}func TestUpdate(t *testing.T) { dsn := "root:abc123@/test?charset=utf8&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) var out Optimistic db.First(&out, Optimistic{Id: 1}) out.Amount = out.Amount + 10 column := db.Model(&out).Where("id", out.Id).Where("version", out.Version). UpdateColumn("amount", out.Amount). UpdateColumn("version", gorm.Expr("version+1")) fmt.Printf("#######update %v line \n", column.RowsAffected)}
这里咱们创立了一张 t_optimistic
表用于测试,生成的 SQL
也满足乐观锁的要求。
不过思考到这类业务的通用性,每次须要乐观锁更新时都须要这样硬编码并不太适合。对于业务来说其实 version
是多少压根不须要关怀,只有能满足并发更新时的准确性即可。
因而我做了一个封装,最终应用如下:
var out Optimisticdb.First(&out, Optimistic{Id: 1})out.Amount = out.Amount + 10if err = UpdateWithOptimistic(db, &out, nil, 0, 0); err != nil { fmt.Printf("%+v \n", err)}
- 这里的应用场景是每次更新时将
amount
金额加上10
。
这样只会更新一次,如果更新失败会返回一个异样。
当然也反对更新失败时执行一个回调函数,在该函数中实现对应的业务逻辑,同时会应用该业务逻辑尝试更新 N 次。
func BenchmarkUpdateWithOptimistic(b *testing.B) { dsn := "root:abc123@/test?charset=utf8&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { fmt.Println(err) return } b.RunParallel(func(pb *testing.PB) { var out Optimistic db.First(&out, Optimistic{Id: 1}) out.Amount = out.Amount + 10 err = UpdateWithOptimistic(db, &out, func(model Lock) Lock { bizModel := model.(*Optimistic) bizModel.Amount = bizModel.Amount + 10 return bizModel }, 3, 0) if err != nil { fmt.Printf("%+v \n", err) } })}
以上代码的目标是:
将 amount
金额 +10
,失败时再次仍然将金额+10,尝试更新 3
次;通过上述的并行测试,最终查看数据库确认数据并没有产生谬误。
面向接口编程
上面来看看具体是如何实现的;其实真正外围的代码也比拟少:
func UpdateWithOptimistic(db *gorm.DB, model Lock, callBack func(model Lock) Lock, retryCount, currentRetryCount int32) (err error) { if currentRetryCount > retryCount { return errors.WithStack(NewOptimisticError("Maximum number of retries exceeded:" + strconv.Itoa(int(retryCount)))) } currentVersion := model.GetVersion() model.SetVersion(currentVersion + 1) column := db.Model(model).Where("version", currentVersion).UpdateColumns(model) affected := column.RowsAffected if affected == 0 { if callBack == nil && retryCount == 0 { return errors.WithStack(NewOptimisticError("Concurrent optimistic update error")) } time.Sleep(100 * time.Millisecond) db.First(model) bizModel := callBack(model) currentRetryCount++ err := UpdateWithOptimistic(db, bizModel, callBack, retryCount, currentRetryCount) if err != nil { return err } } return column.Error}
具体步骤如下:
- 判断重试次数是否达到下限。
- 获取以后更新对象的版本号,将以后版本号 +1。
- 依据版本号条件执行更新语句。
- 更新胜利间接返回。
更新失败
affected == 0
时,执行重试逻辑。- 从新查问该对象的最新数据,目标是获取最新版本号。
- 执行回调函数。
- 从回调函数中拿到最新的业务数据。
- 递归调用本人执行更新,直到重试次数达到下限。
这里有几个中央值得说一下;因为 Go
目前还不反对泛型,所以咱们如果想要获取 struct
中的 version
字段只能通过反射。
思考到反射的性能损耗以及代码的可读性,有没有更”优雅“的实现形式呢?
于是我定义了一个 interface
:
type Lock interface { SetVersion(version int64) GetVersion() int64}
其中只有两个办法,目标则是获取 struct
中的 version
字段;所以每个须要乐观锁的 struct
都得实现该接口,相似于这样:
func (o *Optimistic) GetVersion() int64 { return o.Version}func (o *Optimistic) SetVersion(version int64) { o.Version = version}
这样还带来了一个额定的益处:
一旦该构造体没有实现接口,在乐观锁更新时编译器便会提前报错,如果应用反射只能是在运行期间能力进行校验。
所以这里在接管数据库实体的便能够是 Lock
接口,同时获取和从新设置 version
字段也是十分的不便。
currentVersion := model.GetVersion()model.SetVersion(currentVersion + 1)
类型断言
当并发更新失败时affected == 0
,便会回调传入进来的回调函数,在回调函数中咱们须要实现本人的业务逻辑。
err = UpdateWithOptimistic(db, &out, func(model Lock) Lock { bizModel := model.(*Optimistic) bizModel.Amount = bizModel.Amount + 10 return bizModel }, 2, 0) if err != nil { fmt.Printf("%+v \n", err) }
但因为回调函数的入参只能晓得是一个 Lock
接口,并不分明具体是哪个 struct
,所以在执行业务逻辑之前须要将这个接口转换为具体的 struct
。
这其实和 Java
中的父类向子类转型十分相似,必须得是强制类型转换,也就是说运行时可能会出问题。
在 Go
语言中这样的行为被称为类型断言
;尽管叫法不同,但目标相似。其语法如下:
x.(T)x:示意 interface T:示意 向下转型的具体 struct
所以在回调函数中得依据本人的须要将 interface
转换为本人的 struct
,这里得确保是本人所应用的 struct
,因为是强制转换,编译器无奈帮你做校验,具体是否转换胜利得在运行时才晓得。
总结
有须要的敌人能够在这里获取到源码及具体应用形式:
https://github.com/crossoverJie/gorm-optimistic
最近工作中应用了几种不同的编程语言,会发现除了语言本身的语法个性外大部分知识点都是雷同的;
比方面向对象、数据库、IO操作等;所以把握了这些基本知识,学习其余语言天然就能举一反三了。