SnowflakeService.php 787 B

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