31 lines
563 B
Go
31 lines
563 B
Go
package logic
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// RedisLocker uses SET NX EX so multi-instance servers only run one tick.
|
|
type RedisLocker struct {
|
|
rdb *redis.Client
|
|
}
|
|
|
|
func NewRedisLocker(rdb *redis.Client) *RedisLocker {
|
|
if rdb == nil {
|
|
return nil
|
|
}
|
|
return &RedisLocker{rdb: rdb}
|
|
}
|
|
|
|
func (l *RedisLocker) TryLock(ctx context.Context, key string, ttl time.Duration) (bool, error) {
|
|
if l == nil || l.rdb == nil {
|
|
return true, nil
|
|
}
|
|
if ttl <= 0 {
|
|
ttl = time.Minute
|
|
}
|
|
return l.rdb.SetNX(ctx, key, "1", ttl).Result()
|
|
}
|