RedisLock.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Illuminate\Cache;
  3. class RedisLock extends Lock
  4. {
  5. /**
  6. * The Redis factory implementation.
  7. *
  8. * @var \Illuminate\Redis\Connections\Connection
  9. */
  10. protected $redis;
  11. /**
  12. * Create a new lock instance.
  13. *
  14. * @param \Illuminate\Redis\Connections\Connection $redis
  15. * @param string $name
  16. * @param int $seconds
  17. * @param string|null $owner
  18. * @return void
  19. */
  20. public function __construct($redis, $name, $seconds, $owner = null)
  21. {
  22. parent::__construct($name, $seconds, $owner);
  23. $this->redis = $redis;
  24. }
  25. /**
  26. * Attempt to acquire the lock.
  27. *
  28. * @return bool
  29. */
  30. public function acquire()
  31. {
  32. if ($this->seconds > 0) {
  33. return $this->redis->set($this->name, $this->owner, 'EX', $this->seconds, 'NX') == true;
  34. }
  35. return $this->redis->setnx($this->name, $this->owner) === 1;
  36. }
  37. /**
  38. * Release the lock.
  39. *
  40. * @return bool
  41. */
  42. public function release()
  43. {
  44. return (bool) $this->redis->eval(LuaScripts::releaseLock(), 1, $this->name, $this->owner);
  45. }
  46. /**
  47. * Releases this lock in disregard of ownership.
  48. *
  49. * @return void
  50. */
  51. public function forceRelease()
  52. {
  53. $this->redis->del($this->name);
  54. }
  55. /**
  56. * Returns the owner value written into the driver for this lock.
  57. *
  58. * @return string
  59. */
  60. protected function getCurrentOwner()
  61. {
  62. return $this->redis->get($this->name);
  63. }
  64. /**
  65. * Get the name of the Redis connection being used to manage the lock.
  66. *
  67. * @return string
  68. */
  69. public function getConnectionName()
  70. {
  71. return $this->redis->getName();
  72. }
  73. }