go-ayo/common을 gocommon으로 분리
This commit is contained in:
43
locker_redis.go
Normal file
43
locker_redis.go
Normal file
@ -0,0 +1,43 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
)
|
||||
|
||||
var txSetArgs redis.SetArgs = redis.SetArgs{
|
||||
TTL: time.Second * 30,
|
||||
Mode: "NX",
|
||||
}
|
||||
|
||||
type LockerWithRedis struct {
|
||||
key string
|
||||
}
|
||||
|
||||
var ErrTransactionLocked = errors.New("transaction is already locked")
|
||||
var ErrTransactionHSet = errors.New("transaction set is failed by unkwoun reason")
|
||||
|
||||
func (locker *LockerWithRedis) Lock(rc *redis.Client, key string) error {
|
||||
resultStr, err := rc.SetArgs(context.Background(), key, true, txSetArgs).Result()
|
||||
if err != nil && err != redis.Nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(resultStr) <= 0 {
|
||||
// 이미 있네? 락이 걸려있다
|
||||
logger.Println(ErrTransactionLocked, key)
|
||||
return ErrTransactionLocked
|
||||
}
|
||||
|
||||
locker.key = key
|
||||
return nil
|
||||
}
|
||||
|
||||
func (locker *LockerWithRedis) Unlock(rc *redis.Client) {
|
||||
rc.Del(context.Background(), locker.key).Result()
|
||||
}
|
||||
Reference in New Issue
Block a user