SetNXLock.php 552 B

123456789101112131415161718192021222324252627282930313233
  1. <?php
  2. namespace App\Utility;
  3. use Illuminate\Support\Facades\Redis;
  4. class SetNXLock
  5. {
  6. /**
  7. * 获取排他锁
  8. * @param $key
  9. * @param int $time
  10. * @return bool
  11. */
  12. public static function getExclusiveLock($key, $time = 5)
  13. {
  14. $res = Redis::setnx($key, 1);
  15. if ($res) {
  16. Redis::expire($key, $time);
  17. }
  18. return $res;
  19. }
  20. /**
  21. * 释放锁
  22. * @param $key
  23. * @return int
  24. */
  25. public static function release($key)
  26. {
  27. return Redis::del($key);
  28. }
  29. }