Lock attempts to acquire the lock for the specified key with a timeout. If the lock is already held, it returns an error indicating the lock is unavailable. Parameters: - ctx: The context for managing the lock request lifecycle. - timeout: The time-to-live (TTL) for the lock. Returns an error if the
(ctx context.Context, timeout time.Duration)
| 85 | // - timeout: The time-to-live (TTL) for the lock. |
| 86 | // Returns an error if the lock is already held or if there is a Redis error. |
| 87 | func (l *Locker) Lock(ctx context.Context, timeout time.Duration) error { |
| 88 | success, err := l.client.SetNX(ctx, l.key, l.value, timeout).Result() |
| 89 | if err != nil { |
| 90 | return err |
| 91 | } |
| 92 | if !success { |
| 93 | return &lockError{ |
| 94 | err: ErrLockHeld, |
| 95 | msg: fmt.Sprintf("lock for key %s is already held", l.key), |
| 96 | } |
| 97 | } |
| 98 | return nil |
| 99 | } |
| 100 | |
| 101 | // Unlock releases the lock if the calling instance is the lock holder (based on the value). |
| 102 | // The operation is atomic, ensuring only the holder of the lock can release it. |
no outgoing calls