RedisSequenceResolver.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. use Redis;
  11. use RedisException;
  12. class RedisSequenceResolver implements SequenceResolver
  13. {
  14. /**
  15. * The redis client instance.
  16. *
  17. * @var \Redis
  18. */
  19. protected $redis;
  20. /**
  21. * The cache prefix.
  22. *
  23. * @var string
  24. */
  25. protected $prefix;
  26. /**
  27. * Init resolve instance, must connectioned.
  28. *
  29. * @param Redis $redis
  30. */
  31. public function __construct(Redis $redis)
  32. {
  33. if ($redis->ping()) {
  34. $this->redis = $redis;
  35. return;
  36. }
  37. throw new RedisException('Redis server went away');
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function sequence(int $currentTime)
  43. {
  44. $lua = "return redis.call('exists',KEYS[1])<1 and redis.call('psetex',KEYS[1],ARGV[2],ARGV[1])";
  45. if ($this->redis->eval($lua, [($key = $this->prefix.$currentTime), 1, 1000], 1)) {
  46. return 0;
  47. }
  48. return $this->redis->incrby($key, 1);
  49. }
  50. /**
  51. * Set cacge prefix.
  52. *
  53. * @param string $prefix
  54. */
  55. public function setCachePrefix(string $prefix)
  56. {
  57. $this->prefix = $prefix;
  58. return $this;
  59. }
  60. }