redis.go 551 B

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