这个算法的好处很简单可以在每秒产生约400W个不同的16位数字ID(10进制)

demo1

  1. <?php
  2.  
  3. /**
  4. * 雪花算法类
  5. * @package app\helpers
  6. */
  7. class SnowFlake
  8. {
  9. const EPOCH = 1479533469598;
  10. const max12bit = 4095;
  11. const max41bit = 1099511627775;
  12.  
  13. static $machineId = null;
  14.  
  15. public static function machineId($mId = 0) {
  16. self::$machineId = $mId;
  17. }
  18.  
  19. public static function generateParticle() {
  20. /*
  21. * Time - 42 bits
  22. */
  23. $time = floor(microtime(true) * 1000);
  24.  
  25. /*
  26. * Substract custom epoch from current time
  27. */
  28. $time -= self::EPOCH;
  29.  
  30. /*
  31. * Create a base and add time to it
  32. */
  33. $base = decbin(self::max41bit + $time);
  34.  
  35.  
  36. /*
  37. * Configured machine id - 10 bits - up to 1024 machines
  38. */
  39. if(!self::$machineId) {
  40. $machineid = self::$machineId;
  41. } else {
  42. $machineid = str_pad(decbin(self::$machineId), 10, "0", STR_PAD_LEFT);
  43. }
  44.  
  45. /*
  46. * sequence number - 12 bits - up to 4096 random numbers per machine
  47. */
  48. $random = str_pad(decbin(mt_rand(0, self::max12bit)), 12, "0", STR_PAD_LEFT);
  49.  
  50. /*
  51. * Pack
  52. */
  53. $base = $base.$machineid.$random;
  54.  
  55. /*
  56. * Return unique time id no
  57. */
  58. return bindec($base);
  59. }
  60.  
  61. public static function timeFromParticle($particle) {
  62. /*
  63. * Return time
  64. */
  65. return bindec(substr(decbin($particle),0,41)) - self::max41bit + self::EPOCH;
  66. }
  67. }

demo2

  1. public function createID(){
  2. //假设一个机器id
  3. $machineId = 1234567890;
  4.  
  5. //41bit timestamp(毫秒)
  6. $time = floor(microtime(true) * 1000);
  7.  
  8. //0bit 未使用
  9. $suffix = 0;
  10.  
  11. //datacenterId 添加数据的时间
  12. $base = decbin(pow(2,40) - 1 + $time);
  13.  
  14. //workerId 机器ID
  15. $machineid = decbin(pow(2,9) - 1 + $machineId);
  16.  
  17. //毫秒类的计数
  18. $random = mt_rand(1, pow(2,11)-1);
  19.  
  20. $random = decbin(pow(2,11)-1 + $random);
  21. //拼装所有数据
  22. $base64 = $suffix.$base.$machineid.$random;
  23. //将二进制转换int
  24. $base64 = bindec($base64);
  25.  
  26. $id = sprintf('%.0f', $base64);
  27.  
  28. return $id;
  29. }
相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!