Lock.php 1.5 KB

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