redis.go 580 B

123456789101112131415161718192021222324252627282930313233
  1. package locker
  2. import (
  3. "context"
  4. "time"
  5. "github.com/bsm/redislock"
  6. "github.com/redis/go-redis/v9"
  7. )
  8. type Redis struct {
  9. client *redis.Client
  10. mutex *redislock.Client
  11. }
  12. func (*Redis) String() string {
  13. return "redis"
  14. }
  15. // NewRedis 初始化locker
  16. func NewRedis(c *redis.Client) *Redis {
  17. return &Redis{
  18. client: c,
  19. }
  20. }
  21. func (r *Redis) Lock(key string, ttl int64, options *redislock.Options) (*redislock.Lock, error) {
  22. if r.mutex == nil {
  23. r.mutex = redislock.New(r.client)
  24. }
  25. return r.mutex.Obtain(context.TODO(), key, time.Duration(ttl)*time.Second, options)
  26. }