Lock.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace app\common\library;
  13. /**
  14. * 文件阻塞锁
  15. * Class Lock
  16. * @package app\common\library
  17. */
  18. class Lock
  19. {
  20. // 文件锁资源树
  21. static $resource = [];
  22. /**
  23. * 加锁
  24. * @param $uniqueId
  25. * @return bool
  26. */
  27. public static function lockUp($uniqueId)
  28. {
  29. static::$resource[$uniqueId] = fopen(static::getFilePath($uniqueId), 'w+');
  30. return flock(static::$resource[$uniqueId], LOCK_EX);
  31. }
  32. /**
  33. * 解锁
  34. * @param $uniqueId
  35. * @return bool
  36. */
  37. public static function unLock($uniqueId)
  38. {
  39. if (!isset(static::$resource[$uniqueId])) return false;
  40. flock(static::$resource[$uniqueId], LOCK_UN);
  41. fclose(static::$resource[$uniqueId]);
  42. return static::deleteFile($uniqueId);
  43. }
  44. /**
  45. * 获取锁文件的路径
  46. * @param $uniqueId
  47. * @return string
  48. */
  49. private static function getFilePath($uniqueId)
  50. {
  51. $dirPath = runtime_root_path() . 'lock/';
  52. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  53. return $dirPath . md5($uniqueId) . '.lock';
  54. }
  55. /**
  56. * 删除锁文件
  57. * @param $uniqueId
  58. * @return bool
  59. */
  60. private static function deleteFile($uniqueId)
  61. {
  62. $filePath = static::getFilePath($uniqueId);
  63. return file_exists($filePath) && unlink($filePath);
  64. }
  65. }