https://github.com/crossoverjie/gorm-optimistic
This is an optimistic lock plugin based on GORM.
https://github.com/crossoverjie/gorm-optimistic
golang gorm optimistic-locking
Last synced: 6 months ago
JSON representation
This is an optimistic lock plugin based on GORM.
- Host: GitHub
- URL: https://github.com/crossoverjie/gorm-optimistic
- Owner: crossoverJie
- License: mit
- Created: 2021-03-08T16:28:23.000Z (almost 5 years ago)
- Default Branch: main
- Last Pushed: 2021-06-11T10:50:51.000Z (over 4 years ago)
- Last Synced: 2025-04-17T19:18:37.906Z (9 months ago)
- Topics: golang, gorm, optimistic-locking
- Language: Go
- Homepage:
- Size: 22.5 KB
- Stars: 15
- Watchers: 2
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Gorm optimistic lock
This is an optimistic lock plugin based on [GORM](https://github.com/go-gorm/gorm).
# Installation
```go
go get -u github.com/crossoverJie/gorm-optimistic
```
# Quick start
```go
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
}, 5, 0)
if err != nil {
fmt.Println(err)
}
})
}
```
## Model
```go
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 (o *Optimistic) TableName() string {
return "t_optimistic"
}
func (o *Optimistic) GetVersion() int64 {
return o.Version
}
func (o *Optimistic) SetVersion(version int64) {
o.Version = version
}
```