gorm樂觀鎖使用小結(jié)
前言
樂觀鎖,顧名思義,就是保持樂觀態(tài)度,在數(shù)據(jù)并發(fā)過程中,不會(huì)加鎖,而是在數(shù)據(jù)提交之后,才會(huì)檢查沖突,這通過在數(shù)據(jù)表中增加一個(gè)版本號(version)字段來實(shí)現(xiàn)。如果數(shù)據(jù)在事務(wù)處理期間未被其他事務(wù)修改,那么版本號就不會(huì)發(fā)生變化,事務(wù)可以安全提交。如果版本號發(fā)生變化,說明有沖突發(fā)生,事務(wù)需要回滾或重新嘗試
grom樂觀鎖機(jī)制
gorm樂觀鎖依賴安裝
Gorm是go中一個(gè)優(yōu)秀持久化框架,也提供了樂觀鎖機(jī)制,通過以下命令安裝依賴
go get -u gorm.io/plugin/optimisticlock
gorm樂觀鎖使用
在定義實(shí)體類過程中,通過加上一個(gè)Version版本號控制
import "gorm.io/plugin/optimisticlock"
type User struct {
Id int64 `gorm:"primary_key;type:bigint(20);not null;column:id;comment:'主鍵id';" json:"id"`
UserName string `gorm:"column:userName"`
Sex int `gorm:"column:sex"`
Version optimisticlock.Version
CreateTime time.Time `gorm:"column:create_time;datetime(3);autoUpdateTime" json:"createTime"` // 創(chuàng)建時(shí)間
UpdatedTime time.Time `gorm:"column:update_time;datetime(3);autoUpdateTime" json:"updateTime"` // 更新時(shí)間
}
創(chuàng)建一個(gè)user表
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` bigint NOT NULL AUTO_INCREMENT COMMENT '\'主鍵id\'', `userName` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL, `sex` bigint NULL DEFAULT NULL, `version` bigint NULL DEFAULT NULL, `create_time` datetime(3) NULL DEFAULT NULL, `update_time` datetime(3) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;
插入數(shù)據(jù)
插入一條id為2的數(shù)據(jù)
package main
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"log"
"time"
)
import "gorm.io/plugin/optimisticlock"
type User struct {
Id int64 `gorm:"primary_key;type:bigint(20);not null;column:id;comment:'主鍵id';" json:"id"`
UserName string `gorm:"column:userName"`
Sex int `gorm:"column:sex"`
Version optimisticlock.Version
CreateTime time.Time `gorm:"column:create_time;datetime(3);autoUpdateTime" json:"createTime"` // 創(chuàng)建時(shí)間
UpdatedTime time.Time `gorm:"column:update_time;datetime(3);autoUpdateTime" json:"updateTime"` // 更新時(shí)間
}
func main() {
dsn := "root:root@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: true, // 使用單數(shù)表名
},
})
if err != nil {
log.Println("連接數(shù)據(jù)庫錯(cuò)誤:", err)
return
}
var user = User{
UserName: "aaa",
Sex: 1,
}
result := db.Table("user").Create(&user)
log.Println(result)
log.Println(user)
//var user1 User
//db.Table("user").First(&user1, "id = ?", 1)
//log.Println(user1)
//user1.UserName = "bbbb"
//result1 := db.Table("user").Save(&user1)
//fmt.Println(result1)
}

這時(shí)候版本為1
版本號更新
這時(shí)候把id=2的數(shù)據(jù)查出來,進(jìn)行更新操作,版本號會(huì)發(fā)生變化
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"log"
"time"
)
import "gorm.io/plugin/optimisticlock"
type User struct {
Id int64 `gorm:"primary_key;type:bigint(20);not null;column:id;comment:'主鍵id';" json:"id"`
UserName string `gorm:"column:userName"`
Sex int `gorm:"column:sex"`
Version optimisticlock.Version
CreateTime time.Time `gorm:"column:create_time;datetime(3);autoUpdateTime" json:"createTime"` // 創(chuàng)建時(shí)間
UpdatedTime time.Time `gorm:"column:update_time;datetime(3);autoUpdateTime" json:"updateTime"` // 更新時(shí)間
}
func main() {
dsn := "root:root@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: true, // 使用單數(shù)表名
},
})
if err != nil {
log.Println("連接數(shù)據(jù)庫錯(cuò)誤:", err)
return
}
var user1 User
db.Table("user").First(&user1, "id = ?", 2)
log.Println(user1)
user1.UserName = "bbbb"
result1 := db.Table("user").Save(&user1)
fmt.Println(result1)
}

這時(shí)候可以看到更新成功,版本號變成2
總結(jié)
樂觀鎖機(jī)制,可以有效保證在并發(fā)過程修改數(shù)據(jù)過程中的不安全問題,但是后面更新失敗的問題,根據(jù)項(xiàng)目,具體問題具體分析
到此這篇關(guān)于gorm樂觀鎖使用小結(jié)的文章就介紹到這了,更多相關(guān)gorm 樂觀鎖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go返回int64類型字段超出javascript Number范圍的解決方法
這篇文章主要介紹了Go返回int64類型字段超出javascript Number范圍的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
全面解析Golang 中的 Gorilla CORS 中間件正確用法
Golang 中使用 gorilla/mux 路由器配合 rs/cors 中間件庫可以優(yōu)雅地解決這個(gè)問題,然而,很多人剛開始使用時(shí)會(huì)遇到配置不生效的問題,本文將詳細(xì)介紹其正確用法,感興趣的朋友一起看看吧2025-07-07

