package gocommon 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 { locked_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.locked_key = key return nil } func (locker *LockerWithRedis) Unlock(rc *redis.Client) { rc.Del(context.Background(), locker.locked_key).Result() }