SwooleSequenceResolver.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /*
  3. * This file is part of the godruoyi/php-snowflake.
  4. *
  5. * (c) Godruoyi <g@godruoyi.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled.
  8. */
  9. namespace Godruoyi\Snowflake;
  10. class SwooleSequenceResolver implements SequenceResolver
  11. {
  12. /**
  13. * The las ttimestamp.
  14. *
  15. * @var null
  16. */
  17. protected $lastTimeStamp = -1;
  18. /**
  19. * The sequence.
  20. *
  21. * @var int
  22. */
  23. protected $sequence = 0;
  24. /**
  25. * The swoole lock.
  26. *
  27. * @var mixed
  28. */
  29. protected $lock;
  30. /**
  31. * The cycle count.
  32. *
  33. * @var int
  34. */
  35. protected $count = 0;
  36. /**
  37. * Init swoole lock.
  38. */
  39. public function __construct()
  40. {
  41. $this->lock = new \swoole_lock(SWOOLE_MUTEX);
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function sequence(int $currentTime)
  47. {
  48. /*
  49. * If swoole lock failure,we return a bit number, This will cause the program to
  50. * perform the next millisecond operation.
  51. */
  52. if (!$this->lock->trylock()) {
  53. if ($this->count >= 10) {
  54. throw new \Exception('Swoole lock failure, Unable to get the program lock after many attempts.');
  55. }
  56. ++$this->count;
  57. return 999999;
  58. }
  59. if ($this->lastTimeStamp === $currentTime) {
  60. ++$this->sequence;
  61. } else {
  62. $this->sequence = 0;
  63. }
  64. $this->lastTimeStamp = $currentTime;
  65. $this->lock->unlock();
  66. return $this->sequence;
  67. }
  68. }