zoukankan      html  css  js  c++  java
  • snowflake 雪花算法 php中 使用demo

    <?php
    /**
     * Snowflake 生成唯一ID算法,固定返回19位
     * User: zc
     * Date: 2020/7/22
     * Time: 15:29
     */
    define('EPOCH',1024528659185); // 当前时间(毫秒)
    define('NUMWORKERBITS', 10);
    define('NUMSEQUENCEBITS', 12);
    define('MAXWORKERID', (-1 ^ (-1 << NUMWORKERBITS)));    // 集群ID + 机器ID, 10位,最多支持1024台机器
    define('MAXSEQUENCE', (-1 ^ (-1 << NUMSEQUENCEBITS)));  // 序列,12位,每台机器每毫秒内最多产生4096个序列号
    class Snowflake
    {
        private $_lastTimestamp;
        private $_sequence = 0;
        private $_workerId = 1;
    
        public function __construct($workerId=1)
        {
            if (($workerId < 0) || ($workerId > MAXWORKERID)) {
                return null;
            }
            $this->_workerId = $workerId;
        }
    
        public function next()
        {
            $ts = $this->timestamp();
            if ($ts == $this->_lastTimestamp) {
                $this->_sequence = ($this->_sequence + 1) & MAXSEQUENCE;
                if ($this->_sequence == 0) {
                    $ts = $this->waitNextMilli($ts);
                }
            } else {
                $this->_sequence = 0;
            }
    
            if ($ts < $this->_lastTimestamp) {
                return 0;
            }
    
            $this->_lastTimestamp = $ts;
    
            $return_pack = $this->pack();
            if(strlen($return_pack) < 19) $return_pack = str_pad($return_pack, 19, '0');
            return $return_pack;
        }
    
        private function pack()
        {
            return ($this->_lastTimestamp << (NUMWORKERBITS + NUMSEQUENCEBITS)) | ($this->_workerId << NUMSEQUENCEBITS) | $this->_sequence;
        }
    
        private function waitNextMilli($ts)
        {
            if ($ts = $this->_lastTimestamp) {
                sleep(0.1);
                $ts = $this->timestamp();
            }
    
            return $ts;
        }
    
        private function timestamp()
        {
            return $this->millitime() - EPOCH;
        }
    
        private function millitime()
        {
            $microtime = microtime();
            $comps = explode(' ', $microtime);
            return sprintf('%d%03d', $comps[1], $comps[0] * 1000);
        }
    }
     $snowflake = new Snowflake();
     $card = $snowflake->next();
     var_dump($card );
    滴水成冰,世间不存在毫无意义的付出,时间终会给你答案。
  • 相关阅读:
    GetBuffer与ReleaseBuffer的用法,CString剖析
    Mysql 关闭自动提交
    Mysql 创建用户和数据库
    老爸陪我去面试——北漂18年(3)
    Java中的“&”和“&&”的区别
    Java常量定义
    利用Java API生成50到100之间的随机数
    Java考查“==”和equals
    列出JDK中常用的Java包
    cognos 配置
  • 原文地址:https://www.cnblogs.com/phper12580/p/14955220.html
Copyright © 2011-2022 走看看