RedisLock.php 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace Illuminate\Cache;
  3. use Illuminate\Contracts\Cache\Lock as LockContract;
  4. class RedisLock extends Lock implements LockContract
  5. {
  6. /**
  7. * The Redis factory implementation.
  8. *
  9. * @var \Illuminate\Redis\Connections\Connection
  10. */
  11. protected $redis;
  12. /**
  13. * Create a new lock instance.
  14. *
  15. * @param \Illuminate\Redis\Connections\Connection $redis
  16. * @param string $name
  17. * @param int $seconds
  18. * @return void
  19. */
  20. public function __construct($redis, $name, $seconds)
  21. {
  22. parent::__construct($name, $seconds);
  23. $this->redis = $redis;
  24. }
  25. /**
  26. * Attempt to acquire the lock.
  27. *
  28. * @return bool
  29. */
  30. public function acquire()
  31. {
  32. $result = $this->redis->setnx($this->name, 1);
  33. if ($result === 1 && $this->seconds > 0) {
  34. $this->redis->expire($this->name, $this->seconds);
  35. }
  36. return $result === 1;
  37. }
  38. /**
  39. * Release the lock.
  40. *
  41. * @return void
  42. */
  43. public function release()
  44. {
  45. $this->redis->del($this->name);
  46. }
  47. }