SnowflakeService.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace App\Services;
  3. use Cache;
  4. use Illuminate\Support\Carbon;
  5. class SnowflakeService
  6. {
  7. public static function byDate(?Carbon $ts = null)
  8. {
  9. if ($ts instanceof Carbon) {
  10. $ts = now()->parse($ts)->timestamp;
  11. } else {
  12. return self::next();
  13. }
  14. $datacenterId = config('snowflake.datacenter_id') ?? random_int(1, 31);
  15. $workerId = config('snowflake.worker_id') ?? random_int(1, 31);
  16. return ((round($ts * 1000) - 1549756800000) << 22)
  17. | ($datacenterId << 17)
  18. | ($workerId << 12)
  19. | 0;
  20. }
  21. public static function next()
  22. {
  23. $seq = Cache::get('snowflake:seq');
  24. if (! $seq) {
  25. Cache::put('snowflake:seq', 1);
  26. $seq = 1;
  27. } else {
  28. Cache::increment('snowflake:seq');
  29. }
  30. if ($seq >= 4095) {
  31. Cache::put('snowflake:seq', 0);
  32. $seq = 0;
  33. }
  34. $datacenterId = config('snowflake.datacenter_id') ?? random_int(1, 31);
  35. $workerId = config('snowflake.worker_id') ?? random_int(1, 31);
  36. return ((round(microtime(true) * 1000) - 1549756800000) << 22)
  37. | ($datacenterId << 17)
  38. | ($workerId << 12)
  39. | $seq;
  40. }
  41. }