optimistic

package module
v0.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 11, 2021 License: MIT Imports: 4 Imported by: 0

README

Gorm optimistic lock

This is an optimistic lock plugin based on GORM.

Installation

go get -u github.com/crossoverJie/gorm-optimistic

Quick start

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

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
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func UpdateWithOptimistic

func UpdateWithOptimistic(db *gorm.DB, model Lock, callBack func(model Lock) Lock, retryCount, currentRetryCount int32) (err error)

Types

type Error added in v0.0.5

type Error struct {
	Msg string
}

func NewOptimisticError added in v0.0.5

func NewOptimisticError(msg string) *Error

func (*Error) Error added in v0.0.5

func (e *Error) Error() string

type Lock added in v0.0.2

type Lock interface {
	SetVersion(version int64)
	GetVersion() int64
}

type Version

type Version struct {
	Version int64 `gorm:"column:version;default:0;NOT NULL" json:"version"` // version
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL