LockCache.php 1016 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. namespace App\Cache\Lock;
  3. use App\Consts\BaseConst;
  4. use App\Libs\Utils;
  5. use Illuminate\Support\Facades\Redis;
  6. /**
  7. * 命令参考链接: http://doc.redisfans.com/string/set.html
  8. * 命令 SET resource-name anystring NX EX max-lock-time 是一种在 Redis 中实现锁的简单方法。
  9. * Class LockCache
  10. * @package App\Cache\Lock
  11. */
  12. class LockCache
  13. {
  14. /**
  15. * @param $token
  16. * @param int $seconds
  17. * @return mixed
  18. */
  19. public static function getLock($token, $seconds = BaseConst::LOCK_DEFAULT_SECONDS)
  20. {
  21. $cacheKey = Utils::getCacheKey('lock.token', [$token]);
  22. return Redis::set($cacheKey, $token, 'nx', 'ex', $seconds);
  23. }
  24. /**
  25. * @param $token
  26. * @return int
  27. */
  28. public static function releaseLock($token)
  29. {
  30. $cacheKey = Utils::getCacheKey('lock.token', [$token]);
  31. $result = Redis::get($cacheKey);
  32. if ($result === $token) {
  33. return Redis::del($cacheKey);
  34. }
  35. return 0;
  36. }
  37. }