写了一个 gorm 乐观锁插件

前言

最近在用 Go 写业务的时碰到了并发更新数据的场景,因为该业务并发度不高,只是为了防止出现并发时数据异常。mysql

因此天然就想到了乐观锁的解决方案。git

实现

乐观锁的实现比较简单,相信大部分有数据库使用经验的都能想到。github

UPDATE `table` SET `amount`=100,`version`=version+1 WHERE `version` = 1 AND `id` = 1

须要在表中新增一个相似于 version 的字段,本质上咱们只是执行这段 SQL,在更新时比较当前版本与数据库版本是否一致。sql

如上图所示:版本一致则更新成功,而且将版本号+1;若是不一致则认为出现并发冲突,更新失败。数据库

这时能够直接返回失败,让业务重试;固然也能够再次获取最新数据进行更新尝试。编程


咱们使用的是 gorm 这个 orm 库,不过我查阅了官方文档却没有发现乐观锁相关的支持,看样子后续也不打算提供实现。json

不过借助 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 Optimistic
db.First(&out, Optimistic{Id: 1})
out.Amount = out.Amount + 10
if 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操做等;因此掌握了这些基本知识,学习其余语言天然就能举一反三了。

公众号名片底部.jpg