Lock.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. * 用于并发情况下保持数据的原子性, 仅适用于轻量并发场景,如果是高并发场景请使用redis
  16. * Class Lock
  17. * @package app\common\library
  18. */
  19. class Lock
  20. {
  21. // 文件锁资源树
  22. static $resource = [];
  23. /**
  24. * 加锁
  25. * @param string $uniqueId
  26. * @return bool
  27. */
  28. public static function lockUp(string $uniqueId): bool
  29. {
  30. clearstatcache();
  31. static::$resource[$uniqueId] = fopen(static::getFilePath($uniqueId), 'w+');
  32. return flock(static::$resource[$uniqueId], LOCK_EX);
  33. }
  34. /**
  35. * 解锁
  36. * @param string $uniqueId
  37. * @return bool
  38. */
  39. public static function unLock(string $uniqueId): bool
  40. {
  41. clearstatcache();
  42. if (!isset(static::$resource[$uniqueId])) return false;
  43. flock(static::$resource[$uniqueId], LOCK_UN);
  44. fclose(static::$resource[$uniqueId]);
  45. return static::deleteFile($uniqueId);
  46. }
  47. /**
  48. * 获取锁文件的路径
  49. * @param string $uniqueId
  50. * @return string
  51. */
  52. private static function getFilePath(string $uniqueId): string
  53. {
  54. clearstatcache();
  55. $dirPath = runtime_root_path() . 'lock/';
  56. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  57. return $dirPath . md5($uniqueId) . '.lock';
  58. }
  59. /**
  60. * 删除锁文件
  61. * @param string $uniqueId
  62. * @return bool
  63. */
  64. private static function deleteFile(string $uniqueId): bool
  65. {
  66. clearstatcache();
  67. $filePath = static::getFilePath($uniqueId);
  68. return file_exists($filePath) && unlink($filePath);
  69. }
  70. }