使用SnowFlake演算法產生唯一ID

來源:互聯網
上載者:User

標籤:ret   UI   dom   figure   源碼   ace   64bit   http   log   

轉自:1190000007769660

考慮過的方法有

  • 直接用時間戳記,或者以此衍生的一系列方法

  • Mysql內建的uuid

以上兩種方法都可以查到就不多做解釋了

最終選擇了Twitter的SnowFlake演算法

這個演算法的好處很簡單可以在每秒產生約400W個不同的16位元字ID(10進位)

原理很簡單

ID由64bit組成

其中 第一個bit空缺

41bit用於存放毫秒級時間戳記

10bit用於存放機器id

12bit用於存放自增ID

除了最高位bit標記為不可用以外,其餘三組bit佔位均可浮動,看具體的業務需求而定。預設情況下41bit的時間戳記可以支援該演算法使用到2082年,10bit的工作機器id可以支援1023台機器,序號支援1毫秒產生4095個自增序列id。

下面是PHP源碼

 

 

<?phpnamespace App\Services;abstract class Particle {    const EPOCH = 1479533469598;    const max12bit = 4095;    const max41bit = 1099511627775;    static $machineId = null;    public static function machineId($mId = 0) {        self::$machineId = $mId;    }    public static function generateParticle() {        /*        * Time - 42 bits        */        $time = floor(microtime(true) * 1000);        /*        * Substract custom epoch from current time        */        $time -= self::EPOCH;        /*        * Create a base and add time to it        */        $base = decbin(self::max41bit + $time);        /*        * Configured machine id - 10 bits - up to 1024 machines        */        if(!self::$machineId) {            $machineid = self::$machineId;        } else {            $machineid = str_pad(decbin(self::$machineId), 10, "0", STR_PAD_LEFT);        }                /*        * sequence number - 12 bits - up to 4096 random numbers per machine        */        $random = str_pad(decbin(mt_rand(0, self::max12bit)), 12, "0", STR_PAD_LEFT);        /*        * Pack        */        $base = $base.$machineid.$random;        /*        * Return unique time id no        */        return bindec($base);    }    public static function timeFromParticle($particle) {        /*        * Return time        */        return bindec(substr(decbin($particle),0,41)) - self::max41bit + self::EPOCH;    }}?>

 

調用方法如下

Particle::generateParticle($machineId);//產生ID
Particle::timeFromParticle($particle);//反向計算時間戳記

這裡我做了改良 如果機器ID傳0 就會去掉這10bit 因為有些時候我們可能用不到這麼多ID

 

使用SnowFlake演算法產生唯一ID

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.