Lock.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace app\common\library;
  3. /**
  4. * 文件阻塞锁
  5. * Class Lock
  6. * @package app\common\library
  7. */
  8. class Lock
  9. {
  10. // 文件锁资源树
  11. static $resource = [];
  12. /**
  13. * 加锁
  14. * @param $uniqueId
  15. * @return bool
  16. */
  17. public static function lockUp($uniqueId)
  18. {
  19. static::$resource[$uniqueId] = fopen(static::getFilePath($uniqueId), 'w+');
  20. return flock(static::$resource[$uniqueId], LOCK_EX);
  21. }
  22. /**
  23. * 解锁
  24. * @param $uniqueId
  25. * @return bool
  26. */
  27. public static function unLock($uniqueId)
  28. {
  29. if (!isset(static::$resource[$uniqueId])) return false;
  30. flock(static::$resource[$uniqueId], LOCK_UN);
  31. fclose(static::$resource[$uniqueId]);
  32. return static::deleteFile($uniqueId);
  33. }
  34. /**
  35. * 获取锁文件的路径
  36. * @param $uniqueId
  37. * @return string
  38. */
  39. private static function getFilePath($uniqueId)
  40. {
  41. $dirPath = RUNTIME_PATH . 'lock/';
  42. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  43. return $dirPath . md5($uniqueId) . '.lock';
  44. }
  45. /**
  46. * 删除锁文件
  47. * @param $uniqueId
  48. * @return bool
  49. */
  50. private static function deleteFile($uniqueId)
  51. {
  52. $filePath = static::getFilePath($uniqueId);
  53. return file_exists($filePath) && unlink($filePath);
  54. }
  55. }