UniqueLock.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace Illuminate\Bus;
  3. use Illuminate\Contracts\Cache\Repository as Cache;
  4. class UniqueLock
  5. {
  6. /**
  7. * The cache repository implementation.
  8. *
  9. * @var \Illuminate\Contracts\Cache\Repository
  10. */
  11. protected $cache;
  12. /**
  13. * Create a new unique lock manager instance.
  14. *
  15. * @param \Illuminate\Contracts\Cache\Repository $cache
  16. */
  17. public function __construct(Cache $cache)
  18. {
  19. $this->cache = $cache;
  20. }
  21. /**
  22. * Attempt to acquire a lock for the given job.
  23. *
  24. * @param mixed $job
  25. * @return bool
  26. */
  27. public function acquire($job)
  28. {
  29. $uniqueFor = method_exists($job, 'uniqueFor')
  30. ? $job->uniqueFor()
  31. : ($job->uniqueFor ?? 0);
  32. $cache = method_exists($job, 'uniqueVia')
  33. ? ($job->uniqueVia() ?? $this->cache)
  34. : $this->cache;
  35. return (bool) $cache->lock($this->getKey($job), $uniqueFor)->get();
  36. }
  37. /**
  38. * Release the lock for the given job.
  39. *
  40. * @param mixed $job
  41. * @return void
  42. */
  43. public function release($job)
  44. {
  45. $cache = method_exists($job, 'uniqueVia')
  46. ? ($job->uniqueVia() ?? $this->cache)
  47. : $this->cache;
  48. $cache->lock($this->getKey($job))->forceRelease();
  49. }
  50. /**
  51. * Generate the lock key for the given job.
  52. *
  53. * @param mixed $job
  54. * @return string
  55. */
  56. public static function getKey($job)
  57. {
  58. $uniqueId = method_exists($job, 'uniqueId')
  59. ? $job->uniqueId()
  60. : ($job->uniqueId ?? '');
  61. $jobName = method_exists($job, 'displayName')
  62. ? hash('xxh128', $job->displayName())
  63. : get_class($job);
  64. return 'laravel_unique_job:'.$jobName.':'.$uniqueId;
  65. }
  66. }