LaravelSequenceResolver.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 Illuminate\Contracts\Cache\Repository;
  11. class LaravelSequenceResolver implements SequenceResolver
  12. {
  13. /**
  14. * The laravel cache instance.
  15. *
  16. * @var \Illuminate\Contracts\Cache\Repository
  17. */
  18. protected $cache;
  19. /**
  20. * Init resolve instance, must connectioned.
  21. *
  22. * @param \Illuminate\Contracts\Cache\Repository $cache
  23. */
  24. public function __construct(Repository $cache)
  25. {
  26. $this->cache = $cache;
  27. }
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function sequence(int $currentTime)
  32. {
  33. $store = $this->cache->getStore();
  34. if ($store instanceof \Illuminate\Cache\RedisStore) {
  35. $lua = "return redis.call('exists',KEYS[1])<1 and redis.call('psetex',KEYS[1],ARGV[2],ARGV[1])";
  36. if ($store->connection()->eval($lua, 1, $key = $currentTime, 1, 1000)) {
  37. return 0;
  38. }
  39. return $store->connection()->incrby($key, 1);
  40. }
  41. // Currently we only implement the redis driver, other drivers
  42. // are waiting for your implementation ~_~.
  43. throw new \Exception('Unsupported laravel cache driver.');
  44. }
  45. }