voucher/internal/pkg/lock/mutex.go

32 lines
537 B
Go

package lock
import (
"context"
"github.com/redis/go-redis/v9"
"time"
)
type Mutex struct {
locker *Locker
ttl time.Duration
}
func NewMutex(client *redis.Client, ttl time.Duration) *Mutex {
return &Mutex{
locker: NewLocker(client, ttl, TryLockInterval),
}
}
func (c *Mutex) Lock(ctx context.Context, resource string, callback func(ctx context.Context) error) error {
l := c.locker.GetLock(resource)
if err := l.Lock(ctx); err != nil {
return err
}
defer func() {
_ = l.Unlock(ctx)
}()
return callback(ctx)
}