亲宝软件园·资讯

展开

golang 读写锁

二牛QAQ 人气:0

业务场景

因为项目刚上线,目前暂不打算引入其他中间件,所以打算通过 mysql 来实现分布式读写锁;而该业务场景也满足分布式读写锁的场景,抽象后的业务场景是:特定资源 X,可以执行 2 种操作:读操作和写操作,2种操作需要满足下面条件:

既然需要如此实现,下面我们看下什么是分布式读写锁。

什么是分布式读写锁

大家对于锁肯定不陌生,在 golang 中 sync.Mutex 锁是常见的,一般用在单节点多 goroutine 中对资源的并发访问;但是分布式场景下,单节点 sync.Mutex 加锁的方式就会失去作用,于是人们为了在分布式环境中实现对共享资源的互斥访问,实现了各种分布式锁。

而分布式读写锁是比分布式锁粒度更小的锁,对业务场景的加锁会更加灵活,其中分布式读写锁也遵循读写锁的原则:

分布式读写锁的访问原则与读写锁类似,下面我们具体看下。

分布式读写锁的访问原则

以下列表为读写锁(也就是分布式读写锁)的读写访问原则

当前锁状态读锁请求写锁请求
无锁状态可以可以
读锁状态可以不可以
写锁状态不可以不可以

读锁

写锁

具体实现

如果本地没有 mysql 数据库,可以通过这篇文章快速搭建: 如何使用 docker 搭建一个 mysql 服务

通过 gorm 连接 mysql

gorm 是一个 golang 的 orm 框架,可以使用它快速连接数据库,具体代码如下:

package main

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)
var (
	db *gorm.DB

	dbUsername = "kele"
	dbPassword = "baishi2020"
	dbHost     = "127.0.0.1:7306"
	dbDatabase = "lingmo"

	stateReadLock  = "ReadLock"
	stateWriteLock = "WriteLock"
	stateUnlock    = "Unlock"
)

type RWLock struct {
	LockMark      string `gorm:"default:'Unlock'"`
	ReadLockCount uint32 `gorm:"default:0"`
	LockReason    string
}

type Stock struct {
	gorm.Model
	RWLock
	Count int64
}

func (Stock) TableName() string {
	return "stocks"
}

func init() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", dbUsername, dbPassword, dbHost, dbDatabase)

	mysqlConfig := mysql.Config{DSN: dsn}
	gormConfig := &gorm.Config{Logger: logger.Default.LogMode(logger.Info)}

	var err error
	if db, err = gorm.Open(mysql.New(mysqlConfig), gormConfig); err != nil {
		panic(err)
	}

	db.Set("db:table_options", "ENGINE = InnoDB DEFAULT CHARSET = utf8")

	// register tables
	if err = db.AutoMigrate(&Stock{}); err != nil {
		panic(err)
	}
}

func main() {
	if result := db.Model(&Stock{}).Save(&Stock{Model: gorm.Model{}, RWLock: RWLock{}, Count: 10}); result.Error != nil {
		panic(result.Error)
	}
}

首先我们定义了一个库存表 stocks,并且在其中添加三个和读写锁相关的字段,三个字段的含义如下:

其余则是一些 gorm 连接 mysql 逻辑,这里不再多赘述。

实现读锁模式

具体代码如下:

func (s Stock) RLock(db *gorm.DB, lockReason string) error {
	condition := "(id = ?) AND (lock_mark != ?)"
	fields := map[string]interface{}{
		"lock_mark":       stateReadLock,
		"read_lock_count": gorm.Expr("read_lock_count + ?", 1),
		"lock_reason":     lockReason,
	}

	result := db.Model(&Stock{}).Where(condition, s.ID, stateWriteLock).Updates(fields)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("failed to rlock Stock, RowsAffected=0")
	}

	return nil
}

func (s Stock) RUnlock(db *gorm.DB, UnLockReason string) error {
	sql := fmt.Sprintf(`UPDATE stocks SET read_lock_count=if(read_lock_count>0,read_lock_count-1,0), lock_mark=if(read_lock_count<1, 'Unlock', 'ReadLock'),lock_reason ='%s' where id= %d and lock_mark='%s'`, UnLockReason, s.ID, stateReadLock)
	result := db.Exec(sql)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("failed to RUnlock Stock, RowsAffected=0")
	}

	return nil
}

func main() {
	if result := db.Model(&Stock{}).Save(&Stock{Model: gorm.Model{}, RWLock: RWLock{}, Count: 10}); result.Error != nil {
		panic(result.Error)
	}

	s := &Stock{Model: gorm.Model{ID: 1}}
	if result := db.Model(s).First(s); result.Error != nil {
		panic(result.Error)
	}
	if err := s.RLock(db, "readLock_reason_1"); err != nil {
		panic(err)
	}
	if err := s.RLock(db, "readLock_reason_2"); err != nil {
		panic(err)
	}

	if err := s.RUnlock(db, "readLock_unlock_1"); err != nil {
		panic(err)
	}
	if err := s.RUnlock(db, "readLock_unlock_2"); err != nil {
		panic(err)
	}
}

执行以上代码是可以正常运行的, 下面我们分析下:

UPDATE `stocks` SET `lock_mark` = 'ReadLock', `lock_reason` = 'readLock_reason_1', `read_lock_count` = read_lock_count + 1, `updated_at` = '2022-09-25 14:58:45.693' WHERE (( id = 1 ) 
AND ( lock_mark != 'WriteLock' )) 
AND `stocks`.`deleted_at` IS NULL
UPDATE stocks 
SET read_lock_count =
IF
    ( read_lock_count > 0, read_lock_count - 1, 0 ),
    lock_mark =
IF
    ( read_lock_count < 1, 'Unlock', 'ReadLock' ),
    lock_reason = 'readLock_unlock_1' 
WHERE
    id = 1 
    AND lock_mark = 'ReadLock'

实现写锁模式

具体代码如下:

func (s Stock) WLock(db *gorm.DB, lockReason string) error {
	condition := "(id = ?) AND (lock_mark = ?)"
	fields := map[string]interface{}{
		"lock_mark":       stateWriteLock,
		"read_lock_count": 0,
		"lock_reason":     lockReason,
	}
	result := db.Model(&Stock{}).Where(condition, s.ID, stateUnlock).Updates(fields)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("failed to WLock Stock, RowsAffected=0")
	}

	return nil
}

func (s Stock) WUnlock(db *gorm.DB, UnLockReason string) error {
	condition := "(id = ?) AND (lock_mark = ?)"
	fields := map[string]interface{}{
		"lock_mark":       stateUnlock,
		"read_lock_count": 0,
		"lock_reason":     UnLockReason,
	}

	result := db.Model(&Stock{}).Where(condition, s.ID, stateWriteLock).Updates(fields)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("failed to WUnlock Stock, RowsAffected=0")
	}

	return nil
}

func main() {
	s := &Stock{Model: gorm.Model{ID: 1}}
	if result := db.Model(s).First(s); result.Error != nil {
		panic(result.Error)
	}
	if err := s.WLock(db, "writeLock_reason_1"); err != nil {
		panic(err)
	}
	if err := s.WUnlock(db, "unWriteLock_reason_1"); err != nil {
		panic(err)
	}
}

执行以上代码也是可以运行,下面是分析结果

UPDATE `stocks` SET `lock_mark` = 'WriteLock', `lock_reason` = 'writeLock_reason_1', `read_lock_count` = 0, `updated_at` = '2022-09-25 15:06:10.71' WHERE (( id = 1 ) 
AND ( lock_mark = 'Unlock' )) 
AND `stocks`.`deleted_at` IS NULL
UPDATE `stocks` SET `lock_mark` = 'Unlock', `lock_reason` = 'unWriteLock_reason_1', `read_lock_count` = 0, `updated_at` = '2022-09-25 15:06:10.719' WHERE (( id = 1 ) 
AND ( lock_mark = 'WriteLock' )) 
AND `stocks`.`deleted_at` IS NULL

总结

分布式读写锁的实现有多种方式,也可以通过 etcd、redisson 的方式进行实现,而本文着重说明可通过 mysql 来实现,这种方式的优势在于不必引入额外的组件且实现较为简单,因此也有一定的应用场景,

加载全部内容

相关教程
猜你喜欢
用户评论